Android实现系统消息推送
现在好多应用都接入了推送功能,市面上也有很多关于推送的第三方,例如极光等等,那么我们需求不大,接入极光会造成很大的资源浪费,下面我们来看下利用android服务进行本地推送消息。
1.注册一个Service
importandroid.annotation.TargetApi;
importandroid.app.Notification;
importandroid.app.NotificationManager;
importandroid.app.PendingIntent;
importandroid.app.Service;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.os.Build;
importandroid.os.IBinder;
importjava.util.Calendar;
/**
*Createdby70883on2017/8/10.
*/
publicclassPushSmsServiceextendsService{
privateNotificationManagermanager;
privatePendingIntentpi;
privateMyThreadmyThread;
@Override
publicIBinderonBind(Intentintent){
//TODOAuto-generatedmethodstub
returnnull;
}
@Override
publicvoidonCreate(){
myThread=newMyThread();
myThread.start();
super.onCreate();
}
@Override
publicvoidonDestroy(){
super.onDestroy();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
privatevoidnotification(){
//获取系统的通知管理器
manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intentintent=newIntent(getApplicationContext(),
MainActivity.class);
pi=PendingIntent.getActivity(getApplicationContext(),0,intent,0);
Notificationnotification=newNotification.Builder(getApplicationContext())
.setAutoCancel(true)
.setContentText("工作在忙,也要吃饭哦")
.setContentIntent(pi)
.setSmallIcon(R.mipmap.ic_icon)
.setWhen(System.currentTimeMillis())
.build();
notification.defaults=Notification.DEFAULT_ALL;//使用默认设置,比如铃声、震动、闪灯
notification.flags=Notification.FLAG_AUTO_CANCEL;//但用户点击消息后,消息自动在通知栏自动消失
notification.flags|=Notification.FLAG_NO_CLEAR;//点击通知栏的删除,消息不会依然不会被删除
manager.notify(0,notification);
}
privateclassMyThreadextendsThread{
privateCalendarc;
@Override
publicvoidrun(){
while(true){
c=Calendar.getInstance();
if(c.get(Calendar.HOUR_OF_DAY)==15){
try{
notification();
sleep(1000*60*60);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
}
}
2.在AndroidMan中注册
3.由于我是需要全局应用就在Application中进行启动了
publicvoidstartService(){
Intentintent=newIntent(this,PushSmsService.class);
//启动服务
startService(intent);
}
4.也可以配合服务端使用,定时推送消息
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。