android中的每日通知与警报管理器

时间:2016-01-02 12:19:32

标签: android service notifications alarmmanager

我想为我的Android应用程序创建一个提醒系统,我想每天给用户的手机通知一次。我一直在寻找任何使用AlarmManager的解决方案,我有一段代码如下:

public class TaskActivity extends ActionBarActivity ... {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        periodicNotifier();
    }

    public void periodicNotifier(){
        Intent myIntent = new Intent(this, NotifyService.class);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.add(Calendar.DAY_OF_MONTH, 1);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24*60*60*1000, pendingIntent);
    }

}

这是我的NotifyService类

public class NotifyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        NotificationManager notifManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Intent dest = new Intent(this.getApplicationContext(), TaskActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, dest, 0);

        Notification notification = new Notification.Builder(this)
                .setContentTitle("My Application")
                .setContentText("Go to application now!")
                .setSmallIcon(R.drawable.ic_notif)
                .setContentIntent(pendingIntent)
                .build();

        notifManager.notify(1, notification);
    }
}

我的问题是:

我想每天早上00:00发出通知,我试过这段代码然后将手机的时间改为23:59然后等到00:00但是没有通知。我的代码出了什么问题?或者有任何方法可以做到这一点?

任何答案都将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

你必须尝试这个代码 你必须删除你的AlarmManager,PendingIntent

在你的活动集BroadcastReceiver

private BroadcastReceiver mMessageReceiver;

并且你的onCreate()方法注册你的mMessageReceiver并启动你的服务

registerReceiver(mMessageReceiver, new IntentFilter("time")); 
startService(new Intent(getApplicationContext(), ServiceClockInOut.class));

在你的//处理程序中为" my-event"事件

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String timer = intent.getStringExtra("timer");
         Utils.showNotification(mContext, 1);
    }
};

在您的服务中

public class ServiceClockInOut extends Service {
    // constant
    public static final long NOTIFY_INTERVAL = 5 * 1000; // 10 seconds

    // run on another Thread to avoid crash
    private Handler mHandler = new Handler();
    // timer handling
    private Timer mTimer = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        // cancel if already existed
        if (mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }
        registerReceiver(mMessageReceiver, new IntentFilter("end_time"));
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
    }

class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    // display toast

                    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
                    String currentDateTime = dateTimeFormat.format(new Date()).toString();
                    String[] startSplit = currentDateTime.split(" ");
                    String CurrentTime = startSplit[1] + " " + startSplit[2].toUpperCase();


                    System.out.println("service start-======   " + CurrentTime + " == " + Constant.mStringStartTime
                            + " == " + Constant.mStringBreakTime);

                        Intent intent = new Intent();
                        intent.putExtra("timer", "1");
                        sendBroadcast(intent);



                }

            });
        }

    }
    // handler for received Intents for the "my-event" event
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Extract data included in the Intent
            if (mTimer != null)
                mTimer.cancel();
            unregisterReceiver(mMessageReceiver);
        }
    };
}