AlarmManager无法正常使用 - Android

时间:2016-01-15 11:57:16

标签: android service alarmmanager

在我的情况下,我想重启我的服务以在特定时间段(11秒)从Web服务器获取数据。因此,我使用AlarmManager来实现这一目标。但是,某种程度上它不起作用。

我添加了android.net.conn.CONNECTIVITY_CHANGE Broadcast Receiver。工作正常。 当我从Activity开始服务时。它也像魅力一样开始和运作。

这是我的代码

public class WalletConnectivityService extends Service {

    public static final String TAG = WalletConnectivityService.class.getSimpleName();
    private static boolean started = false;

    public static boolean isStarted() {
        return started;
    }

    /**
     * Factory Method
     */
    public static void start(Context context) {
        if (!isStarted()) {
            context.startService(new Intent(context, WalletConnectivityService.class));
        }
    }

    /**
     * Restart Service Interval
     */
    private static final int REPEAT_TIME_IN_SECONDS = 11 * 1000; // 11 Seconds

    /**
     * Variable for setting Alarm
     */
    private AlarmManager manager;
    private PendingIntent pendingIntent;
    private static boolean isAlarmSet = false;

    public static boolean isAlarmScheduled() {
        return isAlarmSet;
    }

    /**
     * Set the Alarm
     */
    private void setAlarm() {
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, WalletConnectivityService.class), 0);
        manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), REPEAT_TIME_IN_SECONDS,
                pendingIntent);
        isAlarmSet = true;
    }

    /**
     * Cancels the Alarm
     */
    private void cancelAlarm() {
        if (pendingIntent != null && manager != null) {
            manager.cancel(pendingIntent);
            pendingIntent.cancel();
            manager = null;
            pendingIntent = null;
        }
        isAlarmSet = false;
    }

    public WalletConnectivityService() {
        super();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.e(TAG, "onStartCommand");
        started = true;
        if (!Utils.isDeviceOnline(getApplicationContext())) {
            cancelAlarm();
            stopSelf();
        }

        if (!isAlarmScheduled()) {
            setAlarm();
        }

                    // AsyncTask will take place here to get data from web.

        started = false;
        return START_STICKY;
    }

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

1 个答案:

答案 0 :(得分:1)

setAlarm()中,当您创建pendingIntent时,您必须使用PendingIntent.getService(),而不是PendingIntent.getBroadcast()