We do this with our existing app to keep the user within our app even if the home button is hit. I modified the code a little so I could post an example. We are running Android 4.4.3.
You can keep your activity running by running a background service. You keep the task in 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, keep alive with a 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 untested code - so buyer beware.