当前位置: 代码迷 >> Android >> 玩转Android-组件篇-Service(服务)
  详细解决方案

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

热度:337   发布时间:2016-05-01 16:45:54.0
玩转Android---组件篇---Service(服务)

ServiceAndorid系统提供的四大组件之一,它的地位和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

/* * @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

/* * @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如下

<service android:name="MyService">			<intent-filter>				<action android:name="org.hualang.service.action.MYSERVICE"/>			</intent-filter>		</service>

?main.xml布局文件

<?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中显示的信息

?


?
1 楼 lipeng88213 2011-04-11  
没人回复?投个良好 呵呵
2 楼 guoyangjie 2011-04-12  
我也投一票。。。。。。。。。。。。。
3 楼 mini_hu 2011-04-13  
路过,支持一下

+1
4 楼 xici_magic 2011-04-14  
挺不错的  学习啦
5 楼 hot66hot 2011-04-14  
LZ辛苦。
6 楼 songfantasy 2011-04-15  
LZ 是个好人……
  相关解决方案