We do this using our existing application to support the user in our application, even if the home button is pressed. I modified the code a bit to post an example. We are launching Android 4.4.3.
You can keep your activity by running the background service. You keep the task at the forefront of the device. First, get the task id and start the service
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int taskID = getTaskId(); Intent intent = new Intent(this, ServiceKeepInApp.class); intent.putExtra("TaskID", taskId); startService(intent); } }
Your service class will continue to work with the handler:
public class ServiceKeepInApp extends Service { private boolean sendHandler = false; private int taskID = -1; Handler taskHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); ActivityManager activityManager = (ActivityManager)getSystemService(Service.ACTIVITY_SERVICE); if (taskID != -1) { if (activityManager.getRecentTasks(2, 0).get(0).id != taskID) { activityManager.moveTaskToFront(taskID, 0); } } if (sendHandler) { taskHandler.sendEmptyMessageDelayed(0, 1000); } } }; @Override public void onCreate() { Bundle extras = getIntent().getExtras(); if (extras != null) { taskID = extras.getInt("TaskID"); } super.onCreate(); sendHandler = true; taskHandler.sendEmptyMessage(0); } @Override public void onDestroy() { super.onDestroy(); sendHandler = false; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public IBinder onBind(Intent arg0) { return null; } }
This is an unverified code - so beware of the buyer.
source share