摘要:本文将带你了解Android应用开发Android:service详情,希望本文对大家学Android有所帮助。
本文将带你了解Android应用开发Android:service详情,希望本文对大家学Android有所帮助。
我来谈谈我对服务的认识:就是可以把任务放到一个不需要界面的Activity来运行,又区别于Activity,所以就有了service。
比如下载和播放音乐都可以被放到服务里面。
启动服务有两种方式,一种是startService,一种是bindService。
1.启动和停止服务
Intent intent=new Intent(MainActivity.this,MyService.class);
switch (view.getId()){
case R.id.startService:
startService(intent);//启动服务
break;
case R.id.stopService:
stopService(intent);//停止服务
break;
2.绑定和解绑服务
case R.id.bindService:
bindService(intent,connection,BIND_AUTO_CREATE);
break;
case R.id.unbindService:
unbindService(connection);
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
downloadBinder=(MyService.DownloadBinder)iBinder;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d(""csc"",""service unbind"");
}
};
这里需要注意的是服务的onBind返回一个Binder对象,我们就可以在服务里面创建一个内部类,来继承Binder,然后在service中new一下,让这个类变成service的成员变量,这样就可以在服务被绑定到Activity的时候,调用Service的内部成员变量,从而来调用service里面的方法。
private DownloadBinder downloadBinder=new DownloadBinder();
public MyService() {
}
class DownloadBinder extends Binder{
public void startDownload(){
Log.d(""csc"",""startDownload"");
}
public int getProgress(){
Log.d(""csc"",""getProgress"");
return 0;
}
}
注意一点绑定可以绑定多次,解绑只能解绑一次,再次解绑会崩溃。
服务的生命周期,startService的时候,先onCreate(),再onstart(),stopService的时候,onDestroy。
bindService的时候 onCreate(),再onBind,unBindService的时候,onDestroy();
两种方式可以混合,先startService,再BindService,接着UNBindService,最后stopService()
生命周期依次为 onCreate(),onStart(),接着onBind(),然后是Unbind(),最后是onDestroy()
提一点谷歌为我们提供了一个IntentService,来帮助我们处理耗时任务,把子线程创建和stopself()封装为了onHandleIntent方法。
为了方便查看任务下载进度,音乐播放情况,一般会做一个前台service。
在onCreate方法里面添加以下代码就可以了
public void onCreate() {
Log.d(""csc"",""MyService onCreated"");
Intent intent=new Intent(this,MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
Notification notification=new NotificationCompat.Builder(this).setContentTitle(""This is content title"")
.setContentText(""This is content text"").setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentIntent(pi).build();
startForeground(1,notification);
super.onCreate();
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号