安卓的推送一直是一个难题,当然你说简单我也不介意(使用第三方的是很简单)。
这里简单说明一下我这里的实现方案Service+reciver;
其中在service中创建一个进程并保持这个进程不会被系统和第三方清理工具杀死,
在这个进程中隔一段时间就去获取一下服务器的推送信息,
如果不是空,就创建一个Alarm通知reciver去发送通知到通知栏实现推送。
简易代码如下:
//reciver
public class ZLSReciver extends BroadcastReceiver {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) //使用Notification.Builder就需要api16的支持
@Override
public void onReceive(Context context, Intent intent) {
Log.d("DMX", "onReceive");
int intentID = intent.getIntExtra("id", -1);
{
String ticker = intent.getStringExtra("ticker");
String text = intent.getStringExtra("text");
String title = intent.getStringExtra("title");
if (ticker != null && text != null && title != null)
{
Intent intent2Main = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent2Main, 0);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker(ticker)
.setContentText(text)
.setContentTitle(title)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
.setLights(Color.BLUE, 0, 1)
.setAutoCancel(true)
.build();
nm.notify(intentID, notification);//发送通知
}
}}}
receiver的代码看起来并不是很难,只是收到信息就发送一个通知,但是service就并不简单了,这里需要维护一个进程且不会被回收,并同时reciver。下面来看看简化版的service代码。
public class PushService extends Service{
// 获取消息线程
private static MessageThread messageThread = null;
//delete 通知
public void notificationDeleteAll()
{
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
Log.d("PushService", "reg notification service start");
// 开启线程
messageThread = new MessageThread();
messageThread.start();
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId)
{
return super.onStartCommand(intent, flags, startId);
}
class MessageThread extends Thread {
// 设置是否循环推送
public boolean isRunning = true;
public void run() {
while (isRunning) {
if(!isRunning)
{
break;
}
String message = getServermessage();
if(message != null) {
//解析服务器数据并创建alarm发送信息给reciver
}
else
{
//这里维护进程不会被杀死,简单起见就以sleep代替,各位自由发挥吧
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public void onDestroy()
{
messageThread.isRunning = false;
Log.d("PushService","destroy notification service");
super.onDestroy();
}
public String getServermessage()
{
String res = "renult";
return res;
}
}
注意:以上代码只是为说明思路和逻辑的简易代码,只供参考,不可放在项目里面直接运行