現在好多應用都接入了推送功能,市面上也有很多關於推送的第三方,例如極光等等,那麼我們需求不大,接入極光會造成很大的資源浪費,下面我們來看下利用android服務進行本地推送消息,
1.註冊一個Service
package com.baofoo.manshenghuo.ui.Service;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import com.baofoo.manshenghuo.MainActivity;
import com.baofoo.manshenghuo.R;
import java.util.Calendar;
/**
* Created by 70883 on 2017/8/10.
*/
public class PushSmsService extends Service {
private NotificationManager manager;
private PendingIntent pi;
private MyThread myThread;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
myThread = new MyThread();
myThread.start();
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void notification() {
// 獲取系統的通知管理器
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
Notification notification = new Notification.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);
}
private class MyThread extends Thread{
private Calendar c ;
@Override
public void run() {
while (true){
c = Calendar.getInstance();
if(c.get(Calendar.HOUR_OF_DAY) == 15){
try {
notification();
sleep(1000*60*60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
2.在AndroidMan中註冊
<service android:name=".ui.Service.PushSmsService"></service>
3.由於我是需要全局應用就在Application中進行啓動了
public void startService() {
Intent intent = new Intent(this, PushSmsService.class);
// 啓動服務
startService(intent);
}
4.也可以配合服務端使用,定時推送消息