Android_6_Service

#Android_6_Service
Service(服务)是安卓四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件,其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。Service(服务可以脱离前端UI执行在安卓后台,一般这样的service把它叫做后台service,同时service还可以与前端控件绑定运行一般称为前台service,这个的服务会更难被清理,另外一个组件能够绑定到一个service与之进行交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

####Service生命周期
Service启动有两种方式,一种是startService,一种是bind,两种启动方式service的生命同期会有一定差异,在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZfwufMgT-1649401451415)(https://img-my.csdn.net/uploads/201204/17/1334628702_9553.png)]

注:图片引用自博客http://blog.csdn.net/agods/article/details/7468431

####定义Service的步骤

1.创建Service.class继承自系统Service类复写方法

	public class ServiceDemo extends Service {
	    @Override
	    public IBinder onBind(Intent intent) {
	        return null;
	    }
	}

2.在manifest文件中声名服务,在application节点下添加

	<service android:name=".ServiceDemo">
    </service>
	
	这里name属性也可以是全类名,打点缺省应用包名

3.启动service

	Intent intent= new Intent(context,ServiceDemo.class);
    context.startService(intent);
注意: 前台Service如果20秒之内未结束就会出现ANR,后台Service如果200秒之内未结束就会出现ANR,所以不建议在service里面做太过耗时操作

###local service:
######启动一个前台服务:
前台服务顾名思意就是把服务在前台上显示出来,也就是把服务和一个前台显示的控件关联在一起,这样做会提高进程的优先级避免进程被杀

复写onStartCommand()方法

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "onStartCommand()");// 在API11之后构建Notification的方式
		Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
		Intent nfIntent = new Intent(this, MainActivity.class);builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置
		PendingIntent.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_large)) // 设置下拉列表中的图标(大标)
		.setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
		.setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
		.setContentText("要显示的内容") // 设置上下文内容
		.setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
		Notification notification = builder.build(); // 获取构建好的
		Notificationnotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
	}

######启动一个后台服务:
一般是注册一个广播,当接收到广播时,在广播中启动服务

进程间通讯

###remote service:
######aidl(Android Interface Definition Language)
Android翻译:Android interface definition language(aidl)

######在AndroidStudio中使用aidl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值