Android学习之启动Service

Service的生命周期有onCreate,onStart,onDestroy
服务不能自己运行,需要通过调用Context.startService()或Context.bindService()方法启动服务。
  1.通过startService
  Service会经历onCreate->onStart
  stopService的时候直接onDestroy  
  如果是调用者自己直接退出而没有调用stopService的
  话,Service会一直在后台运行。
  2.通过bindService
  系统会先调用服务的 onCreate()方法,接着调用onBind()方法。 
  调用者退出了,Srevice就会调用onUnbind->onDestroyed
  所谓绑定在一起就共存亡了。

如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。
采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。
如果调用bindService()方法前服务已经被绑定,多次调用bindService()方法并不会导致 多次创建服务及绑定(也就是说onCreate()和onBind()方法并不会被多次调用)。
如果调用者希望与正在绑定的服务解除绑定,可以调用 unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()-->onDestroy()方法。

ServiceActivity.java:

package com.demo.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 com.demo.broadcast.R;
import com.demo.service.BindService.MyBinder;

public class ServiceActivity extends Activity implements OnClickListener{

	public static final String TAG = "StartActivity";
    private Button startservice, stopservice, bindservice, unbindservice;
    private boolean flag;
    
    private ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
        	MyBinder binder = (MyBinder)service;
            BindService bindService = binder.getService();
            bindService.MyMethod();
            flag = true;
        }
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("### Service UnBind Scucess .");
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.start);
        flag = false;
        
        startservice = (Button) this.findViewById(R.id.startservice);
        startservice.setOnClickListener(this);
        stopservice = (Button) this.findViewById(R.id.stopservice);
        stopservice.setOnClickListener(this);
        
        bindservice = (Button) this.findViewById(R.id.bindservice);
        bindservice.setOnClickListener(this);
        unbindservice = (Button) this.findViewById(R.id.unbindservice);
        unbindservice.setOnClickListener(this);
    }
    
	@Override
	public void onClick(View v) {
		Intent intent = new Intent(ServiceActivity.this,StartService.class);  
		switch (v.getId()) {
		case R.id.startservice:
			startService(intent);  
			break;
		case R.id.stopservice:
			stopService(intent);
			break;
		case R.id.bindservice:
			bindService();
			break;
		case R.id.unbindservice:
			unbindService();
			break;
		default:
			break;
		}
	}

	private void unbindService() {
		if (flag) {
			Log.i(TAG, "** unbindService");
            unbindService(serviceConnection);
            flag = false;
        }
	}

	private void bindService() {
		Intent intent = new Intent(ServiceActivity.this, BindService.class);
        intent.putExtra("key", "Android BindService");
        bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService();
	}
}

StartService.java:

package com.demo.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class StartService extends Service {
	public static final String TAG = "MyService";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.i(TAG, "** Service onCreate(){}");
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "** Service onDestroy(){}");
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "** Service onStartCommand(){}");
		return super.onStartCommand(intent, flags, startId);
	}

}

BindService.java:

package com.demo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BindService extends Service {
	public static final String TAG = "BindService";
	private IBinder bind = new MyBinder();
	
	public void MyMethod(){
        Log.i(TAG, "BindService-->MyMethod()");
    }

    public class MyBinder extends Binder{
        public BindService getService(){
            return BindService.this;
        }
    }

	@Override
	public IBinder onBind(Intent intent) {
		Log.i(TAG, "*** onBind()");
		Log.i(TAG, "*** DATA = " + intent.getStringExtra("key"));
		return bind;
	}
}

配置文件:

<activity
            android:name="com.demo.service.ServiceActivity"
            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="com.demo.service.StartService"/>
        
<service android:name="com.demo.service.BindService"/>

猜你喜欢

转载自chenzheng8975.iteye.com/blog/2126713
今日推荐