Service
Service是Android系统中的四大组件之一
(Activity、Service、BroadcastReceiver、ContentProvider),它跟Activity的级别差不多,但不能自己运行只能后台运行,并且可以和其他组件进行交互。service可以在很多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务总是藏在后台的, 例如,一个service可能处理网络事物,播放音乐,执行文件I/O,或与一个内容提供者交互,所有这些都在后台进行
Service 运行在系统后台的组件,有独立的生命周期,不可见的后台 Context , 一般不能主动运行,由某个 Context 对象来启动,启动方式有startService 、 bindService
上代码:
public class MusicService extends Service {
//通知管理器
private NotificationManager nm;
public MusicService() {
}
//服务被绑定(到某个Context上)时触发
@Override
public IBinder onBind(Intent intent) {
Log.e("m_tag", "==onBind===");
return new MyBinder();
}
//被解除绑定时触发
@Override
public boolean onUnbind(Intent intent) {
Log.e("m_tag", "==onUnbind===");
return true;
}
//被重新绑定时触发
@Override
public void onRebind(Intent intent) {
Log.e("m_tag", "==onRebind===");
super.onRebind(intent);
}
class MyBinder extends Binder {
public void play(){
}
public MusicService getService() {
return MusicService.this;
}
}
//第一次启动服务,服务创建成功时触发
@Override
public void onCreate() {
Log.e("m_tag", "=====onCreate======");
super.onCreate();
//获取通知管理器
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
showNotification("这是一个通知", "今天你有好运", "你要遇上个小姐姐");
}
//启动端和服务端的通讯入口
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("m_tag", "=====onStartCommand======");
if (intent != null && intent.hasExtra("oop")) {
int oop = intent.getIntExtra("oop", 3);
if (oop == 1) {
//关闭
stopSelf();
}
}
return super.onStartCommand(intent, flags, startId);
}
//销毁服务时触发
@Override
public void onDestroy() {
Log.e("m_tag", "=====onDestroy======");
super.onDestroy();
nm.cancel(333);
}
private void showNotification(String ticker, String contentTitle, String contentText) {
Notification notification;
Intent it = new Intent(this, Activity01.class);
//(Context对象,Intent的id,Intent对象,对Intent的更新方式)
//FLAG_UPDATE_CURRENT表示不销毁原来的PendingIntent,直接替换其中的Intent内容
//FLAG_CANCEL_CURRENT表示取消当前的PendingIntent,重新创建新的PendingIntent对象
PendingIntent pIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
//创建一个远程视图管理
RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.notification_layout);
contentView.setTextViewText(R.id.n_title, contentTitle);
contentView.setTextViewText(R.id.n_content, contentText);//设置文本框中显示的文本内容
contentView.setImageViewResource(R.id.n_icon, R.drawable.not_icon);//设置图片视图
//设置自定义布局中的点击监听
//关闭的Intent,MusicService 进入onStartCommand中
Intent closeIntent = new Intent(this, MusicService.class);
closeIntent.putExtra("oop", 1);
PendingIntent closePdIntent = PendingIntent.getService(this, 2, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.n_close, closePdIntent);
if (Build.VERSION.SDK_INT >= 16) {
Notification.Builder builder = new Notification.Builder(this);
//显示在状态栏上的小图标
builder.setSmallIcon(R.drawable.icon);
//显示在状态栏上的提示文本(显示一段时间消失)
builder.setTicker(ticker);
// //下拉看到的内容标题和文本
// builder.setContentTitle(contentTitle);
// builder.setContentText(contentText);
// //通知时间
// builder.setWhen(System.currentTimeMillis());
builder.setContent(contentView);
//如果点击了内容部分,跳转到Activity01界面
builder.setContentIntent(pIntent);
//创建通知
notification = builder.build();
} else {
notification = new Notification(R.drawable.icon, ticker, System.currentTimeMillis());
notification.contentIntent = pIntent;
notification.contentView = contentView;
}
//自动取消(当通知被点击时,系统会移除通知)
notification.flags = notification.FLAG_AUTO_CANCEL;
notification.defaults = Notification.DEFAULT_ALL;
//显示通知
nm.notify(333, notification);
}
}
绑定端:
//服务连接器
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//绑定成功
MusicService.MyBinder myBinder = (MusicService.MyBinder) service;
MusicService musicService = myBinder.getService();
myBinder.play();
}
@Override
public void onServiceDisconnected(ComponentName name) {
//当绑定了服务,但是服务意外终止时触发
}
};
绑定服务:
Intent it = new Intent(MainActivity.this,MusicService.class);
// 绑定服务, Context.BIND_AUTO_CREATE 表示当绑定的服务还未创建则创建服务对象
bindService(it,conn,Context.BIND_AUTO_CREATE);
解除绑定:
unbindService(conn);
注意:服务在运行中如果涉及到 bindService 的那么在停止服务之前必须 unbindService 才可以停止, bindService 相当于给绑定者 (Context) 和服务之间建立了
Binder 这样的通讯通道, startService 相当于可以直接用 Intent 来通讯