Saturday, February 23, 2019

Android check if home screen (2)

Some app run constantly on Home screen, we need to hide view if there ‘s new app launch. To do this, we need to check if home screen.
In previous post, we use broadcast to check, it make battery soon exhaust.
In this post, we use handler to check.
Declare variables.
private Handler handler = new Handler();
int ra=0;
WindowManager wm;
Create function check like this.
Runnable notification;
     private void check() {
     notification = new Runnable() {
     @TargetApi(Build.VERSION_CODES.GINGERBREAD)
          @SuppressLint("NewApi")
     public void run() {
     ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
String t =am.getRunningTasks(1).get(0).topActivity.getPackageName();
               int d = t.length();
                String duoi = t.substring(d-8, d);                       
                 if(duoi.equals("launcher")){
                  if(ra==1){
                   wm.addView(mView, myParams);
                    ra=0;
                    }
                   }
                   else{
                   if(ra==0){
 ((WindowManager) getSystemService(WINDOW_SERVICE))                                              .removeView(mView);
                   ra=1;
                    }
                   }
               check();
     }
     };
     handler.postDelayed(notification, 1000);
   }
Call inside onCreate();
check();
Add to destroy when exit class.
@Override
    public void onDestroy(){
    handler.removeCallbacks(notification);
       super.onDestroy();
}
Add permission in file manifest.xml
<uses-permission android:name="android.permission.GET_TASKS" />

Detail how to use windowManager to create view see this post.
Test on real phone with same start battery level. If not install app, phone lose 8% battery after 10 hours. If install app with handler check, it lose 11%, app with broadcast lose 71% battery.
This is a strange thing, broadcast make battery exhaust but handler just affect very small.

If we have to use service for always running app, handler is an acceptable way to use.

No comments:

Post a Comment