Android 服务(service)的生命周期以及利用bindservice调用服务里面的方法

服务的生命周期

服务的生命周期跟启动服务的方法有关:
 当采用Context.startService()方法启动服务,与之有关的生命周期方法
onCreate() onStart()  onDestroy()
onCreate()该方法在服务被创建时调用,该方法只会被调用一次,无论调用多少次startService()或bindService()方法,服务也只被创建一次。
onStart() 只有采用Context.startService()方法启动服务时才会回调该方法。该方法在服务开始运行时被调用。多次调用startService()方法尽管不会多次创建服务,但onStart() 方法会被多次调用。
onDestroy()该方法在服务被终止时调用。
 当采用Context.bindService()方法启动服务,与之有关的生命周期方法
onCreate() onBind()  onUnbind()  onDestroy()
onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。
onUnbind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务解除绑定时被调用。
如果先采用startService()方法启动服务,然后调用bindService()方法绑定到服务,再调用unbindService()方法解除绑定,最后调用bindService()方法再次绑定到服务,触发的生命周期方法如下:
onCreate()onStart()onBind()onUnbind()[重载后的方法需返回true]onRebind()

利用bindservice()调用服务里面的方法:

开启服务 (startservice) 
服务一旦开启与调用者没有任何的关系 , 调用着的activity 即便是退出了 不会影响。后台的service的运行.在activity里面 不能去调用服务里面的方法 .

通过绑定方式开启服务(bindservice)

服务跟调用者不求同生 ,但求同死.如果调用者(activity)退出了 那他绑定的服务呢 也会跟着退出.我们可以在activity里面调用服务里面的方法.利用 serviceSonnection 接口 返回一个ibinder对象 , 拿着ibinder对象获取到服务里面方法的引用(自定义了一个接口信息) ,调用服务里面的方法 。


代码示例:

自定义接口IService.java:

package cn.itcast.servicelife;

public interface IService {
	public void callMethodInService();
}
MyService.java:

package cn.itcast.servicelife;

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

public class MyService extends Service {
	// 初始化服务时运行
	@Override
	public IBinder onBind(Intent intent) {

		System.out.println("on bind");
		return new MyBinder();
	}

	public class MyBinder extends Binder implements IService {

		@Override
		public void callMethodInService() {
			sayHelloInService();
		}
	}

	/**
	 * 服务里面的一个方法
	 */
	public void sayHelloInService() {
		System.out.println("hello in service");
	}

	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("on  unbind");
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		System.out.println("oncreate");
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		System.out.println("onstart");

		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		System.out.println("ondestroy");
		super.onDestroy();
	}
}
DemoActivity.java:

package cn.itcast.servicelife;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class DemoActivity extends Activity implements OnClickListener {

	Button bt_start;
	Button bt_stop;
	Button bt_bind_service; // 绑定服务
	Button bt_unbind_service; // 解除绑定服务
	Button bt_call_service;
	Intent intent;
	MyConn conn;
	IService iService;
	int flag = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		bt_start = (Button) this.findViewById(R.id.button1);
		bt_stop = (Button) this.findViewById(R.id.button2);
		bt_bind_service = (Button) this.findViewById(R.id.button3);
		bt_unbind_service = (Button) this.findViewById(R.id.button4);
		bt_call_service = (Button) this.findViewById(R.id.button5);
		bt_start.setOnClickListener(this);
		bt_stop.setOnClickListener(this);
		bt_bind_service.setOnClickListener(this);
		bt_unbind_service.setOnClickListener(this);
		bt_call_service.setOnClickListener(this);
		intent = new Intent(this, MyService.class);
		conn = new MyConn();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1: // 开启服务
			startService(intent);
			break;
		case R.id.button2: // 停止服务
			stopService(intent);
			break;
		case R.id.button3: // 绑定服务
			bindService(intent, conn, Context.BIND_AUTO_CREATE);
			break;
		case R.id.button4: // 解除绑定服务
			if (flag == 0) {
				Toast.makeText(getBaseContext(), "还没有绑定服务,无需解绑", 0).show();
			} else {
				unbindService(conn);
				flag = 0;
			}
			break;
		// 绑定开启
		case R.id.button5: // 调用服务里面的方法
			iService.callMethodInService();
			break;
		}
	}

	private class MyConn implements ServiceConnection {

		// 绑定一个服务成功的时候 调用 onServiceConnected
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			flag = 1;
			iService = (IService) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {

		}
	}

	// DemoActivity的销毁方法
	@Override
	protected void onDestroy() {
		if (flag == 1) {
			unbindService(conn);
		}
		super.onDestroy();
	}
}
清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.itcast.servicelife"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DemoActivity"
            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" >
        </service>
    </application>

</manifest>

问题  ????????????

1.通过实验证明在bindService之后在模拟器的设置中的“正在运行的服务”中找不到相应的服务,是因为和activity绑定的所以不显示吗?

2.在unbindService之后还可以调用服务里面的方法,为什么?服务不是已经被销毁了吗?

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值