我正在使用以下代码定期启动服务,无论应用程序是否为前台。
Intent getAlertIntent = new Intent(getApplicationContext(), GetAlertAlarmReceiver.class);
PendingIntent getAlertpendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, getAlertIntent, 0);
AlarmManager getAlertmanager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
getAlertmanager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, getAlertpendingIntent);
我的接收器的代码如下
public class GetAlertAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, GetAlertServiceIntent.class);
context.startService(i);
}
}
和服务
public class GetAlertServiceIntent extends IntentService {
public GetAlertServiceIntent() {
super("GetAlertServiceIntent");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
protected void onHandleIntent(Intent intent) {
doSomething();
}
}
在我的清单文件中,我将所有内容声明为
<receiver
android:name=".broadcastreceiver.GetAlertAlarmReceiver"
android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="com.surroundapps.shotorkoporibar.services.GetAlertServiceIntent" />
此代码在Marshmallow
以下的API级别中按预期工作,但在棉花糖中它不起作用。