gpt4 book ai didi

android - AlarmManager 在服务中不工作 - Android

转载 作者:行者123 更新时间:2023-11-30 01:38:31 25 4
gpt4 key购买 nike

在我的例子中,我想在特定时间段(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;
}
}

最佳答案

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

关于android - AlarmManager 在服务中不工作 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34810576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com