packagecom.example.notificationservice;importandroid.app.Notification;importandroid.app.NotificationManager;importandroid.app.PendingIntent;importandroid.app.Service;importandroid.content.Context;importandroid.content.Intent;importandroid.os.IBinder;public class NotificationService extendsService {//获取消息线程
private MessageThread messageThread = null;//点击查看
private Intent messageIntent = null;private PendingIntent messagePendingIntent = null;//通知栏消息
private int messageNotificationID = 1000;private Notification messageNotification = null;private NotificationManager messageNotificatioManager = null;publicIBinder onBind(Intent intent) {return null;
}
@Overridepublic int onStartCommand(Intent intent, int flags, intstartId) {//初始化
messageNotification = newNotification();
messageNotification.icon=R.drawable.ic_launcher;
messageNotification.tickerText= "新消息";
messageNotification.defaults=Notification.DEFAULT_SOUND;
messageNotificatioManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
messageIntent= new Intent(this, MainActivity.class);
messagePendingIntent= PendingIntent.getActivity(this, 0,
messageIntent,0);//开启线程
messageThread = newMessageThread();
messageThread.isRunning= true;
messageThread.start();return super.onStartCommand(intent, flags, startId);
}/*** 从服务器端获取消息
**/
class MessageThread extendsThread {//设置是否循环推送
public boolean isRunning = true;public voidrun() {//while (isRunning) {
try{//间隔时间
Thread.sleep(1000);//获取服务器消息
String serverMessage =getServerMessage();if (serverMessage != null && !"".equals(serverMessage)) {//更新通知栏
messageNotification.setLatestEventInfo(
getApplicationContext(),"新消息", "您有新消息。"
+serverMessage, messagePendingIntent);
messageNotificatioManager.notify(messageNotificationID,
messageNotification);//每次通知完,通知ID递增一下,避免消息覆盖掉
messageNotificationID++;
}
}catch(InterruptedException e) {
e.printStackTrace();
}//}
}
}
@Overridepublic voidonDestroy() {//System.exit(0);
messageThread.isRunning = false;super.onDestroy();
}/*** 模拟发送消息
*
*@return返回服务器要推送的消息,否则如果为空的话,不推送*/
publicString getServerMessage() {return "NEWS!";
}
}