我希望通过定期调用API来向用户发送通知,以检查是否有任何挂起通知,用户是否正在使用该应用程序。我想在后台工作24小时。
现在我正在由警报经理来完成这个任务
以下是代码:
服务:
public class NotificationService extends IntentService { 
    public NotificationService() {
        super("NotificationService");
    }
    @Override
    protected void onHandleIntent(Intent intent) { 
        //call api
        sendNotification();
    } 
    private void sendNotification() {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("Hello")
                        .setContentText("Hello World")
                        .setAutoCancel(true); 
        Intent resultIntent = new Intent(this, MainActivity.class);  
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
        mNotificationManager.notify(1, mBuilder.build());
        playNotificationSound();
    }
}接收机
public class NotificationServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent dailyUpdater = new Intent(context, NotificationService.class);
        context.startService(dailyUpdater); 
    }
}AlarmManager
private void setRecurringAlarm(Context context) {
        Calendar updateTime = Calendar.getInstance();
        updateTime.setTimeZone(TimeZone.getDefault()); 
        Intent downloader = new Intent(context, NotificationServiceReceiver.class);
        downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 123546, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), REPEAT_TIME, pendingIntent);
    }问题是,警报管理器有时不工作,当我再次启动应用程序,然后它的统计工作。
发布于 2016-05-06 12:29:09
问题是您的BroadcastReceiver保证运行,但由于省电而不能运行Service。您需要使用一个唤醒锁(请参阅WakefulReceiver上的文档),以确保您的Service有机会运行。本文将提供帮助:http://hiqes.com/android-alarm-ins-outs/
注意,新的Doze模式也会影响到这一点。
https://stackoverflow.com/questions/37071187
复制相似问题