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

标签 android android-intent android-studio android-service

我已经能够在每天的特定时间启动服务,但我想做完全相同的事情来停止,但我不知道如何做。


这是我使用 AlarmManager 启动服务的代码。
注意:我是 android 开发人员的新手,因此非常感谢提供完整的注释代码。

 Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0,
            new Intent(getApplicationContext(), Service.class), PendingIntent.FLAG_NO_CREATE);
    AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);

最佳答案

服务可以从任何正在运行的类中停止,前提是您应该有上下文。 通过以下步骤,您可以使用 Receiver 在特定时间停止正在运行的服务.

<强>1。创建 WakefulBroadcastReceiver类在您的应用程序中。 在接收操作时检查服务是否正在运行,如果运行停止使用 Context

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 设置计划的操作在你的 Activity 课上。

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

希望这对您有所帮助!!

关于android - 如何在一天中的特定时间停止服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973362/

相关文章:

android - 从服务到 Activity 的 ResultReceiver

java - 无法通过蓝牙共享...文件未发送错误

java - 使用 Intent 过滤器从 XML 获取数据的问题

android - 获取重复条目 java.util.zip.ZipException : duplicate entry:

c# - 如何开始使用 C# 编写 iPad、iTouch 和 Android 应用程序?

android - fillWindow() 中的无效语句

java - 报警管理器设置重复失败

android - 无法使用 Superpowered 库为 arm64-v8a 创建 so 文件

java - 为什么我得到 "incompatible types: Object cannot be converted to String"?

android - ListView 中的 RelativeLayout