简单抓取服务器端推送消息的思路

这个推送消息的模型就是从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!";
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值