当用户从当前运行的应用程序列表中删除应用程序时,我想关闭服务。在这里,我正在做的事情是,当用户启动应用程序时,服务就会启动并保持进行中。但是,当用户通过滑动删除应用程序时,就会创建新服务。我想关闭该服务。下面是我的代码。
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
5000, pintent);
startService(new Intent(getBaseContext(), MyService.class));
MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
int count = 0;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
count++;
Toast.makeText(this, " Service Started" + " " + count, Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}