I want to kill my app after 10 second, I want to start service that kill app after getting Kill Action. But this code noting after 10 second. Why?
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, service_MyService.class);
intent.setAction("Kill");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 10);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),pendingIntent);
In your code you are sending a broadcast intent
PendingIntent.getBroadcast(this, 0,intent, 0);
Which can only start a BroadCastReceiver and not a service. However, you are using the right intent, because AlarmManager can not wake up a services, only BroadCastReceiver-s.
You should create a BroadCastReceiver instead of a service, and replace this line:
Intent intent = new Intent(this, service_MyService.class);
with this line
Intent intent = new Intent(this, KillerBroadCastReceiver.class);
and then in your KillerBroadCastReceiver class you kill the app.
However if you want to kill the app after some time, a better solution is to use a Handler. Here is an example:
public class VeryFirstActivity extends Activity {
Handler mKillerHandler;
public void onCreate(...) {
mKillerHandler = new Handler();
mKillerHandler.postDelayed(new Runnable() {
public void run() {
VeryFirstActivity.this.finish();
}
}, 10000); // 10 seconds
}
}
This is not good because Android want to manage application by it self but you can do it like this.
System.exit(0);
You may kill your activity by using:
finish();
Or you can kill your app:
System.exit(0);
But both are not suggested. Android system is not suitable for this. Android OS controls to kill apps.
More information is here