Service实例

下面通过一个实例演示如何创建、启动、停止及绑定一个Service,具体步骤:

1、创建一个工程,在main.xml中声明四个Button,分别用来启动Service、停止Service、绑定Service和接触绑定Service

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<LinearLayout 
		android:orientation="horizontal"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<Button android:id="@+id/startButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="启动"/>
		<Button android:id="@+id/stopButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="停止"/>
	</LinearLayout>
	
	<LinearLayout 
		android:orientation="horizontal"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<Button android:id="@+id/bindButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="绑定"/>
		<Button android:id="@+id/unbindButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="解除绑定"/>
	</LinearLayout>
	
</LinearLayout>

 

2、创建一个MyService,继承自Service,覆盖其生命周期中的方法(onCreate、onStart、onDestroy),并在各个方法中显示信息

public class MyService extends Service{

	/* (non-Javadoc)
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		Log.i("Service", "onBind...");
		Toast.makeText(MyService.this, "OnBind...", Toast.LENGTH_LONG).show() ;
		return null;
	}

	@Override
	public void onCreate() {
		Log.i("Service", "onCreate...");
		Toast.makeText(MyService.this, "onCreate...", Toast.LENGTH_LONG).show() ;
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.i("Service", "onDestroy...");
		Toast.makeText(MyService.this, "onDestroy...", Toast.LENGTH_LONG).show() ;
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i("Service", "onStart...");
		Toast.makeText(MyService.this, "onStart...", Toast.LENGTH_LONG).show() ;
		super.onStart(intent, startId);
	}
}

 

3、在AndroidManifest.xml配置文件中声明activity和service

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.newcosoft.service"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<service android:name="MyService">
			<intent-filter>
				<action android:name="com.newcosoft.service.action.MY_SERVICE"></action>
			</intent-filter>
		</service>
    </application>
</manifest>

 

4、接下来在MainActivity分别创建四个OnClickListener监听和ServiceConnection

public class MainActivity extends Activity {
	private Button startButton,stopButton,bindButton,unbindButton;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startButton = (Button) this.findViewById(R.id.startButton);
        stopButton = (Button) this.findViewById(R.id.stopButton);
        bindButton = (Button) this.findViewById(R.id.bindButton);
        unbindButton = (Button) this.findViewById(R.id.unbindButton);
        
        startButton.setOnClickListener(startOnClickListener);
        stopButton.setOnClickListener(stopOnClickListener);
        bindButton.setOnClickListener(bindOnClickListener);
        unbindButton.setOnClickListener(unbindOnClickListener);
        
    }
    //启动Service监听器
    private OnClickListener startOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			startService(intent);
		}
    	
    };
    
    //停止Service监听器
    private OnClickListener stopOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			stopService(intent);
		}
    	
    };
    
    //创建连接对象
    private ServiceConnection conn = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i("MainActivity", "onServiceConnected");
			Toast.makeText(MainActivity.this, "连接成功!", Toast.LENGTH_LONG);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i("MainActivity", "onServiceDisconnected");
			Toast.makeText(MainActivity.this, "断开连接成功!", Toast.LENGTH_LONG);
		}
    	
    };
    
    //绑定Service监听器
    private OnClickListener bindOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			//指定自动创建
			bindService(intent, conn, BIND_AUTO_CREATE);
		}
    	
    };
    
    //接触绑定Service监听器
    private OnClickListener unbindOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			unbindService(conn);
		}
    	
    };
    
    
}

 

运行结果如下:



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值