Android中Service组件详解 .(转载)
Service是Android的四大组件之一,以下是我结合Android Doc和网上资料的学习总结,有不准确的地方请高手指出,互相学习嘛。。。
这篇文章讲的非常好 http://www.2cto.com/kf/201404/296058.html
1.Service是什么
Service是Android的四大组件之一,即Android系统的服务(不是一个线程,是主程序的一部分),与Activity不同,它是不能与用户交互的,不能自己启动的,需要调用Context.startService()来启动,运行后台,如果我们退出应用时,Service进程并没有结束,它仍然在后台行。比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我们就听不到歌了,所以这时候就得用到Service了。
2.Service生命周期
①onCreate() 创建Service
②onStart(Intent intent, int startId) 启动Service
③onDestroy() 销毁Service
④onBind() 返回一个IBinder接口对象给Service
3.启动和停止Service
①启动:startService(Intent intent)来启动Service,这时Service会调用自身的onCreate()方法(该Service未创建),接着调用onStart()方法。
②停止:stopService(Intent intent)来停止Service,这时Service会调用自身的onDestory()方法。
4.绑定Service
调用bindService(Intent service, ServiceConnection conn, int flags)来绑定一个Service,这时Service会调用自身的onCreate()方法(该Service未创建),接着调用onBind()方法返回客户端一个IBinder接口对象。(注意:如果返回null,ServiceConnection对象的方法将不会被调用)
参数①service:Intent对象 。
参数②conn:ServiceConnection对象,实现其onServiceConnected()和onServiceDisconnected()在连接成功和断开连接时处理。
参数③flags:Service创建的方式,一般用Service.BIND_AUTO_CREATE表示绑定时自动创建。
5.示例代码,下载android_service.rar
MainActivity用来操作Service
view plain copy to clipboard print ?
- publicclassMainActivityextendsActivity{
- privateButtonstartBtn;
- privateButtonstopBtn;
- privateButtonbindBtn;
- privateButtonunBindBtn;
- privatestaticfinalStringTAG="MainActivity";
- privateLocalServicemyService;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- startBtn=(Button)findViewById(R.id.start);
- stopBtn=(Button)findViewById(R.id.stop);
- bindBtn=(Button)findViewById(R.id.bind);
- unBindBtn=(Button)findViewById(R.id.unbind);
- startBtn.setOnClickListener(newMyOnClickListener());
- stopBtn.setOnClickListener(newMyOnClickListener());
- bindBtn.setOnClickListener(newMyOnClickListener());
- unBindBtn.setOnClickListener(newMyOnClickListener());
- }
- classMyOnClickListenerimplementsOnClickListener{
- @Override
- publicvoidonClick(Viewv){
- Intentintent=newIntent();
- intent.setClass(MainActivity.this,LocalService.class);
- switch(v.getId()){
- caseR.id.start:
- //启动Service
- startService(intent);
- break;
- caseR.id.stop:
- //停止Service
- stopService(intent);
- break;
- caseR.id.bind:
- //绑定Service
- bindService(intent,conn,Service.BIND_AUTO_CREATE);
- break;
- caseR.id.unbind:
- //解除Service
- unbindService(conn);
- break;
- }
- }
- }
- privateServiceConnectionconn=newServiceConnection(){
- @Override
- publicvoidonServiceConnected(ComponentNamename,IBinderservice){
- Log.e(TAG,"连接成功");
- //当Service连接建立成功后,提供给客户端与Service交互的对象(根据AndroidDoc翻译的,不知道准确否。。。。)
- myService=((LocalService.LocalBinder)service).getService();
- }
- @Override
- publicvoidonServiceDisconnected(ComponentNamename){
- Log.e(TAG,"断开连接");
- myService=null;
- }
- };
- }
Service实体类
view plain copy to clipboard print ?
- publicclassLocalServiceextendsService{
- privatestaticfinalStringTAG="MyService";
- privatefinalIBindermyBinder=newLocalBinder();
- @Override
- publicIBinderonBind(Intentintent){
- Log.e(TAG,"onBind()");
- Toast.makeText(this,"onBind()",Toast.LENGTH_SHORT).show();
- returnmyBinder;
- }
- //调用startService方法或者bindService方法时创建Service时(当前Service未创建)调用该方法
- @Override
- publicvoidonCreate(){
- Log.e(TAG,"onCreate()");
- Toast.makeText(this,"onCreate()",Toast.LENGTH_SHORT).show();
- }
- //调用startService方法启动Service时调用该方法
- @Override
- publicvoidonStart(Intentintent,intstartId){
- Log.e(TAG,"onStart()");
- Toast.makeText(this,"onStart()",Toast.LENGTH_SHORT).show();
- }
- //Service创建并启动后在调用stopService方法或unbindService方法时调用该方法
- @Override
- publicvoidonDestroy(){
- Log.e(TAG,"onDestroy()");
- Toast.makeText(this,"onDestroy()",Toast.LENGTH_SHORT).show();
- }
- //提供给客户端访问
- publicclassLocalBinderextendsBinder{
- LocalServicegetService(){
- returnLocalService.this;
- }
- }
- }
需要在AndroidManifest.xml中注册建立的Service
view plain copy to clipboard print ?
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="com.snail"android:versionCode="1"android:versionName="1.0">
- <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
- <activityandroid:name=".MainActivity"android:label="@string/app_name">
- <intent-filter>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- <!--注册Service-->
- <serviceandroid:name="LocalService">
- <intent-filter>
- <actionandroid:name="com.snail.LocalService"/>
- </intent-filter>
- </service>
- </application>
- </manifest>
布局文件main.xml
view plain copy to clipboard print ?
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <Buttonandroid:id="@+id/start"android:layout_width="wrap_content"
- android:layout_height="wrap_content"android:text="启动Service"/>
- <Buttonandroid:id="@+id/stop"android:layout_width="wrap_content"
- android:layout_height="wrap_content"android:text="停止Service"/>
- <Buttonandroid:id="@+id/bind"android:layout_width="wrap_content"
- android:layout_height="wrap_content"android:text="绑定Service"/>
- <Buttonandroid:id="@+id/unbind"android:layout_width="wrap_content"
- android:layout_height="wrap_content"android:text="解除Service"/>
- </LinearLayout>
程序运行截图:
依次点击四个按钮后的打印日志:
更多相关文章
- android中实现view的更新UI有两组方法的问题
- Could not find SDK_Root\tools\adb.exe 的解决方法
- Android高手进阶教程(八)-------Android中两种设置全屏的方法!!!
- Android Studio导入.so库文件方法
- (转)Android 应用程序退出后不在运行列表中显示的方法
- android 数据双向绑定学习笔记
- Android Gallery控件使用方法详解