Friday, February 22, 2019

Prevent class from exit

We need to keep always running app never been quit, we use onStop to reopen.
@Override
     public void onStop() {
          super.onStop();
     Intent i=new Intent(this,MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    i.putExtra("ID_TimeLeft",String.valueOf(0));
    startActivity(i);
   }

Second way, create a check function like this.
public static boolean isRunning(Context context) {
     ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
         if (myclass.class.getName().equals(service.service.getClassName())){
            return true;
        }
     }
       return false;
}

Add these lines in to above last close bracket.
boolean running=true;
@Override
     public void onWindowFocusChanged(boolean hasFocus) {
          super.onWindowFocusChanged(hasFocus);
          if (!hasFocus) {
               running=isRunning(this);
               if(running==false){
              finish();
          Intent i=new Intent(this,myclass.class);
            startActivity(i);
            running=true;   
   }


Now app will reopen when closed for any reason.

No comments:

Post a Comment