Android本地定时通知

转载请注明:http://blog.csdn.net/u012854870/article/details/68944598

首先要实现本地定时通知最主要的是要用到系统的AlarmManager来实现的。
推荐几篇关于AlarmManager相关的文章(http://yuanzhifei89.iteye.com/blog/1131523),(http://blog.csdn.net/ryantang03/article/details/9317499)和(http://blog.csdn.net/yelangjueqi/article/details/9002238)

要实现通知肯定相关的知识也需要掌握,如果对通知不太了解的可以参考这篇文章Notification作者也将最新的通知的用法介绍了

接下来我们开始添加一个定时通知任务:20秒后放送一条本地通知

long start = System.currentTimeMillis() + 20 * 1000;
Intent intent = new Intent(mContext, RemindActionService.class);
intent.putExtra("id", 10);
intent.putExtra("title", "测试");
intent.putExtra("contentText", "测试本地通知");
PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am= (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, start , pendingIntent);

其中RemindActionService为接收系统通知的service,其实这里可以用BroadcastReceiver实现只需要将PendingIntent.getService替换成PendingIntent.getBroadcast然后实现一个RemindBroadcastReceiver类去接收通知。

接下来我们来建RemindActionService然后写其中的实现代码:


public class RemindActionService extends Service {
    private Context mContext;
    private NotificationManager notificationManager;
    private Notification.Builder mBuilder;
    private Notification notification;

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

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new Notification.Builder(mContext);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intent2=new Intent();
        intent2.setClass(this, MainActivity.class);//点击通知需要跳转的activity
        PendingIntent contentIntent = PendingIntent.getActivity(mContext,0, intent2,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification = mBuilder.setContentTitle(intent.getStringExtra("title"))
                .setContentText(intent.getStringExtra("contentText"))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
                .setContentIntent(contentIntent)
                .setDefaults(Notification.DEFAULT_SOUND)
                .build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
        return START_REDELIVER_INTENT;
    }


}

最后别忘记在Manifest中对Service进行注册

至此实现本地定时通知的代码就全部写完了。
最后给出一个用BroadcastReceiver实现的例子地址:(http://www.cnblogs.com/lycokcc/p/4112214.html)

猜你喜欢

转载自blog.csdn.net/u012854870/article/details/68944598