只要您具有上下文,就可以从任何正在运行的类中停止服务.
通过以下步骤,您可以使用
Receiver在特定时间停止正在运行的服务.
1.在您的应用程序中创建一个WakefulBroadcastReceiver类.在接收操作时检查服务是否正在运行,如果使用上下文运行停止.
public class TestReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase("STOP_TEST_SERVICE")) {
if (isMyServiceRunning(context, TestService.class)) {
Toast.makeText(context,"Service is running!! Stopping...",Toast.LENGTH_LONG).show();
context.stopService(new Intent(context, TestService.class));
}
else {
Toast.makeText(context,"Service not running",Toast.LENGTH_LONG).show();
}
}
}
private boolean isMyServiceRunning(Context context,Class> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
2.在AndroidManifest中注册接收器.
3.使用所需操作创建PendingIntent,然后在活动类中使用AlarmManager设置计划操作.
public void setStopServiceAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
new Intent().setAction("STOP_TEST_SERVICE"), PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
希望这可以帮助!!