Friday, February 22, 2019

Run class constantly on screen.

If we have a always running on screen app, we need to check if activity has been send to background, for example user press Home button, we bring it back to foreground.
Create a service.
public class newse extends Service {
 private static final int INTERVAL = 3000; // poll every 3 secs
 private static final String YOUR_APP_PACKAGE_NAME = "com.example.vidu";
   private static boolean stopTask;
    private PowerManager.WakeLock mWakeLock;
    @Override
    public void onCreate() {
        super.onCreate();
        stopTask = false;
       
     final ActivityManager activityManager = (ActivityManager) this
                        .getSystemService(Context.ACTIVITY_SERVICE);
        // Start your (polling) task
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // If you wish to stop the task/polling
                if (stopTask){
                    this.cancel();
                }
List<ActivityManager.RunningAppProcessInfo> tasks = activityManager.getRunningAppProcesses();
String foregroundTaskPackageName = tasks.get(0).processName;
// Check foreground app: If it is not in the foreground... bring it!
if (!foregroundTaskPackageName.equals(YOUR_APP_PACKAGE_NAME)) {
Intent LaunchIntent = getPackageManager()
          .getLaunchIntentForPackage(YOUR_APP_PACKAGE_NAME);
                     startActivity(LaunchIntent);
               }
            }
        };
    Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, 0, INTERVAL);
   }
    @Override
    public void onDestroy(){
        stopTask = true;
        if (mWakeLock != null)
            mWakeLock.release();
        super.onDestroy();
    }
     @Override
     public IBinder onBind(Intent intent) {
          // TODO Auto-generated method stub
          return null;
     }
}

String YOUR_APP_PACKAGE_NAME must be your package name.
Declare service in to file AndroidManifest.xml, above last </application>.
<service
android:name=".newse"
android:enabled="true"
android:exported="false"/>
In class need to bring back, add these lines to above last close bracket.
@Override
     public void onWindowFocusChanged(boolean hasFocus) {
          super.onWindowFocusChanged(hasFocus);
          if (!hasFocus) {
     Intent intent = new Intent(this, newse.class);
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     startService(intent);         
     }
     }

After call service, we need to close when done, if not, it will make phone battery exhaust.
Intent intent = new Intent(this, newse.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
stopService(intent);
You can use only the line stopService(intent), but sometime you must create function to ensure it closed.

We need to listen 3 button Back, Home, Menu, call service when detect button pressed.

No comments:

Post a Comment