android在特定时间,android – 如何在一天中的特定时间停止服务?

只要您具有上下文,就可以从任何正在运行的类中停止服务.

通过以下步骤,您可以使用

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);

}

}

希望这可以帮助!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值