概述: java
首先簡單闡述一下我對於消息推送的理解,這裏拿QQ來舉例吧,當咱們手機端的QQ離線了,而且退出了QQ應用,可是這時候若是別人給咱們發了信息,咱們沒有上線。服務器會將發送者發送的信息推送過來而後咱們發佈通知來顯示通知咱們的用戶 android
原理簡單闡述: 服務器
經過以上概述,咱們基本瞭解咱們須要一個獨立進程的後臺服務,在AndroidManifest app
.xml中註冊Service時,有一個android:process屬性這個屬性有2種狀況,即爲.和:兩種,其中.表明爲此服務開啓一個全局的獨立進程,若是以:開頭則爲此服務開啓一個爲此應用私有的獨立進程 ide
編碼實現: 測試
ServerPushService文件: this
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class ServerPushService extends Service{ //獲取消息線程 private MessageThread messageThread = null; //點擊查看 private Intent messageIntent = null; private PendingIntent messagePendingIntent = null; //通知欄消息 private int messageNotificationID = 1000; private Notification messageNotification = null; private NotificationManager messageNotificationManager = null; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //初始化 messageNotification = new Notification(); messageNotification.icon = R.drawable.ic_launcher; //通知圖片 messageNotification.tickerText = "新消息"; //通知標題 messageNotification.defaults = Notification.DEFAULT_SOUND; messageNotificationManager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE); //點擊查看 messageIntent = new Intent(this,MessageActivity.class); messagePendingIntent = PendingIntent.getActivity(this, 0, messageIntent, 0); //開啓線程 MessageThread thread = new MessageThread(); thread.isRunning = true; thread.start(); return super.onStartCommand(intent, flags, startId); } /*** * 從服務端獲取消息 * @author zhanglei * */ class MessageThread extends Thread{ //運行狀態 public boolean isRunning = true; @Override public void run() { while(isRunning){ try { //休息10秒 Thread.sleep(10000); if(getServerMessage().equals("yes")){ //設置消息內容和標題 messageNotification.setLatestEventInfo(ServerPushService.this, "您有新消息!", "這是一條新的測試消息", messagePendingIntent); //發佈消息 messageNotificationManager.notify(messageNotificationID, messageNotification); //避免覆蓋消息,採起ID自增 messageNotificationID++; } } catch (Exception e) { e.printStackTrace(); } } } } /*** * 模擬了服務端的消息。實際應用中應該去服務器拿到message * @return */ public String getServerMessage(){ return "yes"; } }
<!-- 爲此應用私有的獨立進程 --> <service android:name="com.jay.serverpush.ServerPushService" android:process=":message" > </service>
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.startService(new Intent(this,ServerPushService.class)); } this.startService(new Intent(this,ServerPushService.class));經過這句話在第一次進入oncreate方法就開啓了單獨進程的服務