AlarmManager设置失败

时间:2017-02-13 08:26:22

标签: android

我的问题是当我设置2分钟后的时间是10:02,当我重启设备几次,可能是时间是10:03或10:04或10:05,我的通知总是显示出来每次。

我希望我的通知在10:02之后只显示一次,是否警报管理器无法将其用于系统?

如果是这样,我该如何避免这个问题?任何帮助将不胜感激。

我使用了alarmManager,SharePreferenes,BroadcastReceiver。

我的主要活动按钮功能:

public void onClickSetup(View view)
    {
        Toast.makeText(this,"Starting setting",Toast.LENGTH_SHORT).show();

        Calendar cal = Calendar.getInstance();
        // after 2 minutes
        cal.add(Calendar.MINUTE, 2);

        Intent intent = new Intent(this, PlayReceiver.class);
        intent.putExtra("msg", "play_hskay");

        PendingIntent pi = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);

        long time=cal.getTimeInMillis();
        //Save the time for future
        SharedPreferences preferences=getSharedPreferences("time",MODE_PRIVATE);
        preferences.edit().putLong("saveTime",time)
                .apply();
    }

我的接收通知:

public class PlayReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bData = intent.getExtras();
        if (bData.get("msg").equals("play_hskay")) {


            Intent notificationIntent = new Intent(context, MainActivity.class);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(notificationIntent);
            PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

            inboxStyle.addLine("message");

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

            Notification notification;
            notification = mBuilder.setSmallIcon(R.drawable.heart).setTicker("title").setWhen(0)
                    .setAutoCancel(true)
                    .setContentTitle("title")
                    //.setContentIntent(resultPendingIntent)
                    //.setSound(alarmSound)
                    .setStyle(inboxStyle)
                    //.setWhen(getTimeMilliSes(timeStamp))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    //.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setContentText("title")
                    .setContentIntent(pendingIntent)
                    .build();

            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0 , notification);
        }
    }

}

我的接收器重启设备:

public class AlarmInitReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context,"Start~~~~",Toast.LENGTH_LONG).show();
        // load system time for now. May be is 10:03、10:04、10:05
        long current = Calendar.getInstance().getTimeInMillis();
        // load the time when i set it before.
        SharedPreferences preferences = context.getSharedPreferences("time", context.MODE_PRIVATE);
        long setTime = preferences.getLong("saveTime", 0);


            Toast.makeText(context,"Enter receiver setting",Toast.LENGTH_LONG).show();

            Intent intentForSetTime = new Intent(context, PlayReceiver.class);
            intentForSetTime.putExtra("msg", "play_hskay");

            PendingIntent pi = PendingIntent.getBroadcast(context, 1, intentForSetTime, PendingIntent.FLAG_ONE_SHOT);

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, setTime, pi);//setTime suppose is 10:02

    }
}

我的广播清单:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<receiver android:name=".PlayReceiver">
            <intent-filter>
                <action android:name="play_hskay" />
            </intent-filter>
        </receiver>

    <receiver android:name=".AlarmInitReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

2 个答案:

答案 0 :(得分:1)

在这种情况下,在不改变代码的情况下,只需在警报事件发生时向sharedprefs添加标志,即调用PlayReceiver。

如果在重新启动之前发生了警报,那么boot_completed接收器将检查prefs中的标志是否已经完成。

然后可以相应地设置/不设置警报。

干杯... !!

   public void onClickSetup(View view)
    {
        Toast.makeText(this, "Starting setting", Toast.LENGTH_SHORT).show();

        Calendar cal = Calendar.getInstance();
        // after 2 minutes
        cal.add(Calendar.MINUTE, 2);

        Intent intent = new Intent(this, PlayReceiver.class);
        intent.putExtra("msg", "play_hskay");

        PendingIntent pi = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);

        long time=cal.getTimeInMillis();
        //Save the time for future
        //Code Edit
        SharedPreferences preferences=getPreferences(MODE_PRIVATE);
        preferences.edit().putBoolean("received",false).commit();
    }





public class PlayReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bData = intent.getExtras();
        if (bData.get("msg").equals("play_hskay")) {


            Intent notificationIntent = new Intent(context, MainActivity.class);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(notificationIntent);
            PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

            inboxStyle.addLine("message");

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

            Notification notification;
            notification = mBuilder.setSmallIcon(R.drawable.heart).setTicker("title").setWhen(0)
                    .setAutoCancel(true)
                    .setContentTitle("title")
                            //.setContentIntent(resultPendingIntent)
                            //.setSound(alarmSound)
                    .setStyle(inboxStyle)
                            //.setWhen(getTimeMilliSes(timeStamp))
                    .setSmallIcon(R.mipmap.ic_launcher)
                            //.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setContentText("title")
                    .setContentIntent(pendingIntent)
                    .build();

            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0 , notification);

            //Code Edit

            SharedPreferences preferences=getPreferences(MODE_PRIVATE);
            preferences.edit().putBoolean("received",true).commit();
        }
    }

}




public class AlarmInitReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        //Code Edit
        SharedPreferences preferences=getPreferences(MODE_PRIVATE);
        boolean isReceived=preferences.getBoolean("received",false);

        if(!isReceived)
        {
            Toast.makeText(context,"Start~~~~",Toast.LENGTH_LONG).show();
            // load system time for now. May be is 10:03、10:04、10:05
            long current = Calendar.getInstance().getTimeInMillis();
            // load the time when i set it before.
            SharedPreferences preferences = context.getSharedPreferences("time", context.MODE_PRIVATE);
            long setTime = preferences.getLong("saveTime", 0);


            Toast.makeText(context,"Enter receiver setting",Toast.LENGTH_LONG).show();

            Intent intentForSetTime = new Intent(context, PlayReceiver.class);
            intentForSetTime.putExtra("msg", "play_hskay");

            PendingIntent pi = PendingIntent.getBroadcast(context, 1, intentForSetTime, PendingIntent.FLAG_ONE_SHOT);

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, setTime, pi);//setTime suppose is 10:02

        }
    }
}

答案 1 :(得分:-1)

对于我的代码我只需要启动服务..我已经使用过..

public void scheduleAlarm() {
        // Construct an intent that will execute the AlarmReceiver
        Intent intent = new Intent(this, LocationListnerServiec.class);
        // Create a PendingIntent to be triggered when the alarm goes off
        final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Setup periodic alarm every 5 seconds
        long firstMillis = System.currentTimeMillis(); // alarm is set right away
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
        // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
                60000, pIntent);
    }

和MyAlaramReciver类

public class MyAlarmReceiver extends BroadcastReceiver {
    public static final int REQUEST_CODE = 12345;
    // Triggered by the Alarm periodically (starts the service to run task)
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, LocationListnerServiec.class);
        i.putExtra("foo", "bar");
        context.startService(i);
        //Toast.makeText(context, "Welcome --------1", Toast.LENGTH_LONG).show();
    }
}

试试可能会对你有帮助。