经过固定时间后如何停止我的服务?

How to stop my service after passing fixed amount of time?

在我的应用程序的 A 点,我启动了我的服务并期望服务从 B 点关闭。但是,可能很少有 B 点不要求服务关闭的情况。在这种情况下,我希望服务在固定时间后自行关闭。

我已将以下代码写入我的服务 class 并预计服务会在启动时间 10 秒后关闭(未来将是 45 分钟,但我不想停留那么久进行测试).

public class ChatService extends Service implements ITCPConnection
{
    private static final int SERVICE_LIFE_TIME = 10 * 1000; // In millis

    private AlarmReceiver mAlarmReceiver;
    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;

    @Override
    public void onCreate()
    {
        super.onCreate();

        //
        mAlarmReceiver = new AlarmReceiver();
        registerReceiver(mAlarmReceiver, new IntentFilter());

        //
        Intent intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + SERVICE_LIFE_TIME, alarmIntent);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.e(TAG, "onDestroy()");

        // Unregister receiver
        if (mAlarmReceiver != null)
        {
            unregisterReceiver(mAlarmReceiver);
        }

        disconnect();
    }

    public void disconnect()
    {
        // If the alarm has been set, cancel it.
        if (alarmMgr!= null)
        {
            alarmMgr.cancel(alarmIntent);
        }

        ...

        Log.e(TAG, "disconnect()");
    }


    /*****************
     * Alarm Receiver
     *****************/
    private static class AlarmReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Log.e(TAG, "Stop service from AlarmReceiver");
            context.stopService(intent);
        }
    }
}

我的问题是 AlarmReceiver.onReceive() 永远不会被调用,因此我的服务将无限期地存在。

您要做的是明确定位广播接收器。

根据 this,它不能通过动态创建的(即未声明到清单中的)广播接收器完成,因为 os 不知道如何解析它。 要检查这是否是问题的根源,您可以使用隐式方式并在 intent 中设置一个操作,然后在 IntentFilter 中对其进行过滤。

无论如何,使用 post delayed 可以被视为一个有效的替代方案,因为您希望服务自然关闭或仍然存在以拦截延迟事件。

另一件(不相关的)事情是你打电话给

            context.stopService(intent);

通过使用广播意图而不是启动服务的意图。您可以简单地调用 stopSelf().