只要您有上下文,就可以从任何正在运行的类中停止服务。
通过以下步骤,您可以使用 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 中注册接收器。
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="STOP_TEST_SERVICE" />
<action android:name="START_TEST_SERVICE" />
</intent-filter>
</receiver>
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);
}
}
希望这有帮助!