您的位置:首页 > 移动开发 > Android开发

android 一个简单的服务例子

2015-01-26 23:31 267 查看
public class MessageService extends Service {

// 获取消息线程
private MessageThread messageThread = null;

// 点击查看
private Intent messageIntent = null;
private PendingIntent messagePendingIntent = null;

// 通知栏消息
private int messageNotificationID = 1000;
private Notification messageNotification = null;
private NotificationManager messageNotificatioManager = null;
private final IBinder binder = new MessageService.LocalBinder();

@Override
public IBinder onBind(final Intent intent) {
return binder;
}

// 定义内容类继承Binder
class LocalBinder extends Binder {
// 返回本地服务
// 可以返回这个服务,然后<bold>activity可以通过服务调用服务的方法</bold>了。
MessageService getService() {
return MessageService.this;
}

}

@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
// 初始化
messageNotification = new Notification();
messageNotification.icon = R.drawable.ic_launcher;
messageNotification.tickerText = "新消息";
messageNotification.defaults = Notification.DEFAULT_SOUND;
messageNotificatioManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

messageIntent = new Intent(this, MessageActivity.class);
messagePendingIntent = PendingIntent.getActivity(this, 0,
messageIntent, 0);

// 开启线程
messageThread = new MessageThread();
messageThread.isRunning = true;
messageThread.start();

return super.onStartCommand(intent, flags, startId);
}

/**
* 从服务器端获取消息
*
*/
class MessageThread extends Thread {
// 运行状态,下一步骤有大用
public boolean isRunning = true;

@Override
public void run() {
while (isRunning) {
try {
// 休息15s
Thread.sleep(15 * 1000);
// 获取服务器消息
String serverMessage = getServerMessage();
if (serverMessage != null && !"".equals(serverMessage)) {
// 更新通知栏
messageNotification.setLatestEventInfo(
MessageService.this, "新消息", "奥巴马宣布,本拉登兄弟挂了!"
+ serverMessage, messagePendingIntent);
messageNotificatioManager.notify(messageNotificationID,
messageNotification);
// 每次通知完,通知ID递增一下,避免消息覆盖掉
messageNotificationID++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

/**
* 这里以此方法为服务器Demo,仅作示例
*
* @return 返回服务器要推送的消息,否则如果为空 的话,不推送
*/
public String getServerMessage() {
return "YES!";
}

@Override
public void onDestroy() {
System.exit(0);
// 或者,二选一,推荐使用System.exit(0),这样进程退出的更干净
// messageThread.isRunning = false;
super.onDestroy();
}
}


from:源自
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: