我需要编写一个调度程序,它会每隔5分钟更新应用程序数据,我找到了收件人
创建接收器和IntentService但是当我关闭应用程序时它们不起作用。在清单中,它看起来像一个应用程序部分
<receiver android:name=".components.UpdateReceiver" android:process=":remote">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</receiver>
<service android:name=".components.UpdateService"/>
接收者类代码:
public final class UpdateReceiver extends WakefulBroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, UpdateService.class);
startWakefulService(context, service);
}
public void setAlarm(Context context) {
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,UpdateReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
long interval = 5 * 60 *1000;
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
interval,
interval, alarmIntent);
ComponentName receiver = new ComponentName(context, UpdateReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
在我的splash活动中,我创建了UpdateReceiver并调用了set Alarm方法。一切都很好,但当我关闭应用程序时它不起作用。我在Android 6.0设备上测试过可能存在问题。我发现很多教程几乎都是一样的,但是我无法理解错误在哪里?
答案 0 :(得分:0)
从Android 6.0(API级别23)开始,用户在应用运行时向应用授予权限。
您的reciver未被调用,因为Google更改了您在API级别23上获得权限的方式。
我们如何询问权限?
内部活动可见生命周期方法(例如onCreate / onResume):
int MY_PERMISSIONS_REQUEST_ACQUIRE_WAKE_LOCK = 200; //Can be any number that represent OK result code
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WAKE_LOCK
},
MY_PERMISSIONS_REQUEST_ACQUIRE_WAKE_LOCK
);
并在onActivityResult
:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACQUIRE_WAKE_LOCK: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
} else {
// permission denied by user
}
return;
}
}
}