在Android实例代码中,一个通过服务来启动消息通知的damo,代码比较简单
public class NotifyService extends Service {
private ConditionVariable mCondition;//控制消息线程
private NotificationManager mNN;//消息管理器@Override
public void onCreate() {
mNN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//启动线程运行服务,服务正常运行的过程中,主线程不会被阻止
Thread mThread = new Thread(mTask, "NotifyService");
mCondition = new ConditionVariable(false);
mThread.start();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
private Runnable mTask = new Runnable() {
@Override
public void run() {
showNotification(R.drawable.stat_neutral, R.string.hello_world);
mCondition.block(1000* 10);
NotifyService.this.stopSelf();
}
};
private final IBinder mBinder = new Binder();
private void showNotification(int moodId, int textId){
CharSequence text = getText(textId);
Notification notification = new Notification(moodId,text, System.currentTimeMillis());
//PendingIntent 用户点击消息框时启动对应的activity
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
//对消息通知栏设置信息
notification.setLatestEventInfo(this, "你好", text, contentIntent);
//发送消息
//第一个参数是消息的特殊标示,在销毁时使用
mNN.notify(1000, notification);
}
@Override
public void onDestroy() {
mNN.cancel(1000);
mCondition.open();
}
}
public class MainActivity extends Activity {
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, NotifyService.class));
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(MainActivity.this, NotifyService.class));
}
});
}
}