概述: 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方法就开启了单独进程的服务