在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));
}
});
}
}