`
cynhafa
  • 浏览: 154796 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

玩转Android---组件篇---Service(服务)

 
阅读更多

Service是Andorid系统提供的四大组件之一,它的地位和Activity是并列的,只是使用的频率没有Activity高。Service就是运行于后台的一种服务程序,一般很少和用户交互,因此没有可视化界面。

定义一个Service类只要继承Service类即可,实现其生命周期中的方法就可以了,另外,一个定义好的Service组件必须要在AndoridManifest.xml文件中注册才能够使用。

Service有自己的生命周期,可以调用startService()启动一个Service或者使用bindService()来绑定一个service,还可以通过RPC(远程进程调用)机制来实现不同进程间Service的调用。

Service中定义了一系列和自身生命周期相关的方法:

onBind(Intent intent):是必须实现的一个方法,返回一个绑定的接口给Service。

onCreate():当Service第一次被创建时,由系统调用。

onStart(Intent intent,int startId):当通过startService()方法启动Service时,该方法被调用。

onDestroy():当Service不再使用,系统调用该方法。

实例如下:

MyService.java

Java代码 复制代码收藏代码
  1. /*
  2. *@authorhualang
  3. */
  4. packageorg.hualang.service;
  5. importandroid.app.Service;
  6. importandroid.content.Intent;
  7. importandroid.os.IBinder;
  8. importandroid.util.Log;
  9. importandroid.widget.Toast;
  10. publicclassMyServiceextendsService{
  11. @Override
  12. publicIBinderonBind(Intentintent){
  13. //TODOAuto-generatedmethodstub
  14. Log.i("SERVICE","onBind.................");
  15. Toast.makeText(MyService.this,"onBind.................",Toast.LENGTH_LONG).show();
  16. returnnull;
  17. }
  18. publicvoidonCreate()
  19. {
  20. Log.i("SERVICE","onCreate................");
  21. Toast.makeText(MyService.this,"onCreate................",Toast.LENGTH_LONG).show();
  22. }
  23. publicvoidonStart(Intentintent,intstartId)
  24. {
  25. Log.i("SERVICE","onStart.................");
  26. Toast.makeText(MyService.this,"onStart.................",Toast.LENGTH_LONG).show();
  27. }
  28. publicvoidonDestroy()
  29. {
  30. Log.i("SERVICE","onDestroy.................");
  31. Toast.makeText(MyService.this,"onDestroy.................",Toast.LENGTH_LONG).show();
  32. }
  33. }
/* * @author hualang */package org.hualang.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MyService extends Service {	@Override	public IBinder onBind(Intent intent) {		// TODO Auto-generated method stub		Log.i("SERVICE", "onBind.................");		Toast.makeText(MyService.this, "onBind.................", Toast.LENGTH_LONG).show();		return null;	}		public void onCreate()	{		Log.i("SERVICE", "onCreate................");		Toast.makeText(MyService.this, "onCreate................", Toast.LENGTH_LONG).show();	}	public void onStart(Intent intent,int startId)	{		Log.i("SERVICE", "onStart.................");		Toast.makeText(MyService.this, "onStart.................", Toast.LENGTH_LONG).show();	}	public void onDestroy()	{		Log.i("SERVICE", "onDestroy.................");		Toast.makeText(MyService.this, "onDestroy.................", Toast.LENGTH_LONG).show();	}}

ServiceTest.java

Java代码 复制代码收藏代码
  1. /*
  2. *@authorhualang
  3. */
  4. packageorg.hualang.service;
  5. importandroid.app.Activity;
  6. importandroid.app.Service;
  7. importandroid.content.ComponentName;
  8. importandroid.content.Intent;
  9. importandroid.content.ServiceConnection;
  10. importandroid.os.Bundle;
  11. importandroid.os.IBinder;
  12. importandroid.util.Log;
  13. importandroid.view.View;
  14. importandroid.view.View.OnClickListener;
  15. importandroid.widget.Button;
  16. importandroid.widget.Toast;
  17. publicclassServiceTestextendsActivity{
  18. /**Calledwhentheactivityisfirstcreated.*/
  19. privateButtonstartService,stopService,bindService,unbindService;
  20. @Override
  21. publicvoidonCreate(BundlesavedInstanceState){
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.main);
  24. startService=(Button)findViewById(R.id.startButton);
  25. stopService=(Button)findViewById(R.id.stopButton);
  26. bindService=(Button)findViewById(R.id.bindButton);
  27. unbindService=(Button)findViewById(R.id.unbindButton);
  28. startService.setOnClickListener(startListener);
  29. stopService.setOnClickListener(stopListener);
  30. bindService.setOnClickListener(bindListener);
  31. unbindService.setOnClickListener(unbindListener);
  32. }
  33. privateOnClickListenerstartListener=newOnClickListener()
  34. {
  35. @Override
  36. publicvoidonClick(Viewv){
  37. //TODOAuto-generatedmethodstub
  38. Intentintent=newIntent();
  39. intent.setAction("org.hualang.service.action.MYSERVICE");
  40. startService(intent);
  41. }
  42. };
  43. privateOnClickListenerstopListener=newOnClickListener()
  44. {
  45. @Override
  46. publicvoidonClick(Viewv){
  47. //TODOAuto-generatedmethodstub
  48. Intentintent=newIntent();
  49. intent.setAction("org.hualang.service.action.MYSERVICE");
  50. stopService(intent);
  51. }
  52. };
  53. privateServiceConnectionconn=newServiceConnection()
  54. {
  55. @Override
  56. publicvoidonServiceConnected(ComponentNamename,IBinderservice){
  57. //TODOAuto-generatedmethodstub
  58. Log.i("SERVICE","connectionsuccess");
  59. Toast.makeText(ServiceTest.this,"connectionsuccess",Toast.LENGTH_LONG).show();
  60. }
  61. @Override
  62. publicvoidonServiceDisconnected(ComponentNamename){
  63. //TODOAuto-generatedmethodstub
  64. Log.i("SERVICE","connectionsuccess");
  65. Toast.makeText(ServiceTest.this,"connectionfailure",Toast.LENGTH_LONG).show();
  66. }
  67. };
  68. privateOnClickListenerbindListener=newOnClickListener()
  69. {
  70. @Override
  71. publicvoidonClick(Viewv){
  72. //TODOAuto-generatedmethodstub
  73. Intentintent=newIntent();
  74. intent.setAction("org.hualang.service.action.MYSERVICE");
  75. bindService(intent,conn,Service.BIND_AUTO_CREATE);
  76. }
  77. };
  78. privateOnClickListenerunbindListener=newOnClickListener()
  79. {
  80. @Override
  81. publicvoidonClick(Viewv){
  82. //TODOAuto-generatedmethodstub
  83. Intentintent=newIntent();
  84. intent.setAction("org.hualang.service.action.MYSERVICE");
  85. unbindService(conn);
  86. }
  87. };
  88. }
/* * @author hualang */package org.hualang.service;import android.app.Activity;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class ServiceTest extends Activity {    /** Called when the activity is first created. */	private Button startService,stopService,bindService,unbindService;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        startService=(Button)findViewById(R.id.startButton);        stopService=(Button)findViewById(R.id.stopButton);        bindService=(Button)findViewById(R.id.bindButton);        unbindService=(Button)findViewById(R.id.unbindButton);        startService.setOnClickListener(startListener);        stopService.setOnClickListener(stopListener);        bindService.setOnClickListener(bindListener);        unbindService.setOnClickListener(unbindListener);            }    private OnClickListener startListener=new OnClickListener()    {		@Override		public void onClick(View v) {			// TODO Auto-generated method stub			Intent intent=new Intent();			intent.setAction("org.hualang.service.action.MYSERVICE");			startService(intent);		}    	    };    private OnClickListener stopListener=new OnClickListener()    {		@Override		public void onClick(View v) {			// TODO Auto-generated method stub			Intent intent=new Intent();			intent.setAction("org.hualang.service.action.MYSERVICE");			stopService(intent);		}    	    };    private ServiceConnection conn=new ServiceConnection()    {		@Override		public void onServiceConnected(ComponentName name, IBinder service) {			// TODO Auto-generated method stub			Log.i("SERVICE", "connection success");			Toast.makeText(ServiceTest.this, "connection success", Toast.LENGTH_LONG).show();		}		@Override		public void onServiceDisconnected(ComponentName name) {			// TODO Auto-generated method stub			Log.i("SERVICE", "connection success");			Toast.makeText(ServiceTest.this, "connection failure", Toast.LENGTH_LONG).show();		}    	    };    private OnClickListener bindListener=new OnClickListener()    {		@Override		public void onClick(View v) {			// TODO Auto-generated method stub			Intent intent=new Intent();			intent.setAction("org.hualang.service.action.MYSERVICE");			bindService(intent,conn,Service.BIND_AUTO_CREATE);		}    	    };    private OnClickListener unbindListener=new OnClickListener()    {		@Override		public void onClick(View v) {			// TODO Auto-generated method stub			Intent intent=new Intent();			intent.setAction("org.hualang.service.action.MYSERVICE");			unbindService(conn);		}    	    };}

在AndroidManifest.xml文件中注册Service如下

Java代码 复制代码收藏代码
  1. <serviceandroid:name="MyService">
  2. <intent-filter>
  3. <actionandroid:name="org.hualang.service.action.MYSERVICE"/>
  4. </intent-filter>
  5. </service>
<service android:name="MyService">			<intent-filter>				<action android:name="org.hualang.service.action.MYSERVICE"/>			</intent-filter>		</service>

main.xml布局文件

Java代码 复制代码收藏代码
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <Button
  8. android:text="启动Service"
  9. android:id="@+id/startButton"
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. />
  13. <Button
  14. android:text="停止Service"
  15. android:id="@+id/stopButton"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content"
  18. />
  19. <Button
  20. android:text="绑定Service"
  21. android:id="@+id/bindButton"
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. />
  25. <Button
  26. android:text="解除绑定unbindService"
  27. android:id="@+id/unbindButton"
  28. android:layout_width="fill_parent"
  29. android:layout_height="wrap_content"
  30. />
  31. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >	<Button		android:text="启动Service"		android:id="@+id/startButton"		android:layout_width="fill_parent"		android:layout_height="wrap_content"	/>		<Button		android:text="停止Service"		android:id="@+id/stopButton"		android:layout_width="fill_parent"		android:layout_height="wrap_content"	/>		<Button		android:text="绑定Service"		android:id="@+id/bindButton"		android:layout_width="fill_parent"		android:layout_height="wrap_content"	/>		<Button		android:text="解除绑定unbindService"		android:id="@+id/unbindButton"		android:layout_width="fill_parent"		android:layout_height="wrap_content"	/></LinearLayout>

不解释,看运行结果就会明白

(1)当点击“启动Servcie”会先弹出"onCreate",然后弹出"onStart"的Toast,在LogCat中会看到先显示

的也是

onCreate

onStart


(2)点击“停止Service”按钮,会弹出onDestroy的Toast

LogCat中也会显示

onDestroy()



(3)点击"绑定Service"按钮,会弹出onCreate和onBind的Toast

LogCat中显示

onCreate

onBind



(4)点击“解除绑定Service”按钮,会弹出onDestroy的Toast,LogCat中也如此



下面是LogCat中显示的信息


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics