Friday, February 22, 2019

Android check in home screen

Some app run constantly on Home screen, we need to hide view if a new app launch. To do this, we need to check if home screen.
Create a service, set alarm to check every 5 seconds, if top app has package tail name is launcher, we know it is home screen.
Add permission in file manifest.xml.
<uses-permission android:name="android.permission.GET_TASKS" />
Declare to top service.
int ra=0;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
Copy this function in to above last close bracket.
private void setup() {
            br = new BroadcastReceiver() {
                  @Override
                  public void onReceive(Context c, Intent i) {
                        ActivityManager am =
                                     (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
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;
}                                        
}
};
registerReceiver(br, new IntentFilter("com.example.vidu"));
pi = PendingIntent.getBroadcast(this, 0, new Intent("com.example.vidu"),0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 5000, pi);
}
Add this to destroy.
@Override
     public void onDestroy() {
          super.onDestroy();
          am.cancel(pi);
          unregisterReceiver(br);
}
Call function setup() inside onCreate();
My view need to hide name mView.
To create view, see this post.
This way make battery soon be exhausted because it check every 5 seconds. To avoid this, we can use  handler

No comments:

Post a Comment