首先是Android開機自啟動的功能實現,代碼如下:
1. AndroidManifest.xml中添加如下代碼:
<!-- 抓取系統啟動事件 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
…..
<service
android:name="com.demo.notification.NotificationService"
android:icon="@drawable/icon"
android:label="@string/app_name" >
</service>
<receiver android:name="com.demo.notification.MyScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
2. 接著是實現MyScheduleReceiver代碼,這是當Android啟動後會自動啟動的程序。
public class MyScheduleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, NotificationService.class);
context.startService(service);
}
}
3. 實現NotificationService代碼,用來接收推送消息
public class NotificationService extends Service {
private final IBinder mBinder = new MyBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 將接收推送消息任務放入後台執行
new ZeroMQMessageTask().execute();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
public NotificationService getService() {
return NotificationService.this;
}
}
private class ZeroMQMessageTask extends AsyncTask<String, Void, String> {
public ZeroMQMessageTask() {
}
@Override
protected String doInBackground(String... params) {
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL);
subscriber.connect("tcp://x.x.x.x:xxxx");
while (true) { // 通過不終止的循環來保證接收消息
message = subscriber.recvStr();
if (!message.equals("0")) { // 0是由我自己定義的空消息標識,可以替換成自定義的其它標識
// 顯示推送消息
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = "Demo - " + message;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon,
tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Context uiContext = getApplicationContext();
CharSequence contentTitle = "Demo";
CharSequence contentText = message;
Intent notificationIntent = new Intent(uiContext,
NotificationService.class);
PendingIntent contentIntent = PendingIntent
.getActivity(uiContext, 0, notificationIntent, 0);
notification.setLatestEventInfo(uiContext, contentTitle,
contentText, contentIntent);
mNotificationManager.notify(1, notification);
}
}
}
@Override
protected void onPostExecute(String result) {
}
}
}
好啦,重新啟動手機嘗試發條消息吧! :D
服務器端的代碼可以參考此文:http://www.linuxidc.com/Linux/2015-01/112318.htm