通过服务启动消息通知

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值