Android 不在Activity的子類中用主線程的寫法

        在Activity的子類中,可以直接用 runOnUiThread() , 但是如果是在普通類中,就沒這個方法能調用了,最簡單的寫法是用Handler getMainLooper,下邊貼上對比runOnUiThread的寫法:

-        runOnUiThread(new Runnable() {
-            public void run() {
-                wmOne.addView(floatView, params);
-                ObjectAnimator a = ObjectAnimator.ofFloat(floatView.rootView, "translationY", -700, 0);
-                a.setDuration(600);
-                a.start();
-                floatView.setNotification(headsUp);
-                if (headsUp.getNotification() != null) {
-                    headsUp.getBuilder().setFullScreenIntent(null, false);
-                    notificationManager.notify(headsUp.getCode(), headsUp.getNotification());
-                }
-            }
-        });



+        new Handler(context.getMainLooper())
+                .post(()-> {
+                    wmOne.addView(floatView, params);
+                    ObjectAnimator a = ObjectAnimator.ofFloat(floatView.rootView, "translationY", -700, 0);
+                    a.setDuration(600);
+                    a.start();
+                    floatView.setNotification(headsUp);
+                    if (headsUp.getNotification() != null) {
+                        headsUp.getBuilder().setFullScreenIntent(null, false);
+                        notificationManager.notify(headsUp.getCode(), headsUp.getNotification());
+                    }
+                });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章