简单抓取服务器端推送消息的思路
这个推送消息的模型就是从Service启动一个线程,定期获取服务器端消息然后显示出来:
MessageService.java文件:
package com.text.ac; 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.IBinder; public class MessageService extends Service { private Notification mNotification = null; private NotificationManager mNotifyManager = null; private Intent mIntent = null; private PendingIntent mPendingIntent = null; /** 获取消息线程 */ private MessageThread mMsgThread = null; private int messageNotificationID = 1000; public IBinder onBind(Intent intent) { return null; } /** Called by the system when the service is first created. */ @Override public void onCreate() { super.onCreate(); mNotification = new Notification(); /** * The resource id of a drawable to use as the icon in the status bar. * This is required; notifications with an invalid icon resource will * not be shown. */ mNotification.icon = R.drawable.icon; mNotification.tickerText = "新消息"; mNotification.defaults = Notification.DEFAULT_SOUND; mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /** 点击跳转的activity. */ mIntent = new Intent(this, ExTextActivity.class); mPendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0); mMsgThread = new MessageThread(); mMsgThread.isRunning = true; mMsgThread.start(); } class MessageThread extends Thread { public boolean isRunning = true; public void run() { while (isRunning) { try { Thread.sleep(5000); /** 获取服务器消息 . */ String mServerMsg = getServerMessage(); if (mServerMsg != null && !"".equals(mServerMsg)) { /** 更新通知栏. */ mNotification .setLatestEventInfo(MessageService.this, "新消息", "您中奖了,1个亿!" + mServerMsg, mPendingIntent); mNotifyManager.notify(messageNotificationID, mNotification); /** 每次通知完,通知ID递增一下,避免消息覆盖掉. */ messageNotificationID++; } } catch (InterruptedException e) { e.printStackTrace(); } } } } @Override public void onDestroy() { System.exit(0); /** 使用System.exit(0),这样进程退出的更干净. */ mMsgThread.isRunning = false; super.onDestroy(); } /** * 这里以此方法为服务器Demo,仅作示例 * * @return 返回服务器要推送的消息,否则如果为空的话,不推送 */ public String getServerMessage() { return "YES!"; } }
相关推荐
xfcyhades 2020-11-20
刘炳昭 2020-09-10
huha 2020-10-16
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28