Android Service的两种启动方式,你知道吗?

这篇文章我是看到一些前辈的知识整理的,在此声明下。

1.Context.startService()方式启动:

①Context.startService()方式的生命周期: 

启动时,startService –> onCreate() –> onStart();停止时,stopService –> onDestroy()。

如果调用者直接退出而没有停止Service,则Service 会一直在后台运行 Context.startService()方法启动服务,在服务未被创建时,

系统会先调用服务的onCreate()方法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用

startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。采用startService()方法启动的服务,

只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。

2.Context.bindService()方式启动:

①Context.bindService()方式的生命周期:

 绑定时,bindService -> onCreate() –> onBind();调用者退出了,即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory()。

Context.bindService()方式启动 Service的方法:绑定Service需要三个参数:bindService(intent, conn, Service.BIND_AUTO_CREATE);

第一个:Intent对象;第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 onServiceDisconnected()

来判断连接成功或者是断开连接;第三个:如何创建Service,一般指定绑定的时候自动创建。

附代码    

<span style="color:#333333;">package com.dada.test;

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.util.Log;
import android.view.View;
import android.widget.Button;

import com.dada.test.BindService.MyBinder;

public class TestActivity extends Activity {
	
	private boolean flag;
	private static final String TAG = "TestActivity";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
 
        Button btnStart = (Button) findViewById(R.id.btnStart); 
 
        Button btnStop = (Button) findViewById(R.id.btnStop); 
 
        
        btnStart.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
            	//启动service 方式2
            	bindService();
            } 
        }); 
        
        btnStop.setOnClickListener(new View.OnClickListener() { 
        	 
            @Override 
            public void onClick(View v) { 
 //停止service 方式2
            	unBindService();
            } 
        }); 
    }
    
    //启动service 方式2
    //
    private void bindService(){
        Intent intent = new Intent(TestActivity.this,BindService.class);
        Log.i(TAG, "bindService()");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }
    
    private void unBindService(){
    	Log.i(TAG, "unBindService() start....");
        if(flag == true){
        	Log.i(TAG, "unBindService() flag");
            unbindService(conn);
            flag = false;
        }
    }
    
private ServiceConnection conn = new ServiceConnection() {
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        	Log.i(TAG, "onServiceDisconnected()");
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
        	Log.i(TAG, "onServiceConnected()");
            MyBinder binder = (MyBinder)service;
            BindService bindService = binder.getService1();
            bindService.MyMethod();
            flag = true;
        }
    };
}</span>

package com.dada.test;

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 {

    private static final String TAG = "BindService";
    private MyBinder myBinder = new MyBinder();
    public void MyMethod(){
        Log.i(TAG, "BindService-->MyMethod()");
    }
    
    @Override
    public IBinder onBind(Intent intent) {
    	Log.i(TAG, "BindService-->onBind()");
        return myBinder;
    }
    
    public class MyBinder extends Binder{
        
        public BindService getService1(){
            return BindService.this;
        }
    }
    
  

	@Override
	public void onCreate() {
		Log.i(TAG, "BindService-->onCreate()");
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(TAG, "BindService-->onStart()");
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "BindService-->onDestroy()");
		super.onDestroy();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.i(TAG, "BindService-->onUnbind()");
		return super.onUnbind(intent);
	}
	
}

运行日志

点击启动


点击停止


没有打出onServiceDisconnected的日志的原因:

注:SDK上是这么说的:This is called when the connection with the service has been 
unexpectedly disconnected -- that is, its process crashed. Because it is running in our same 
process, we should never see this happen.

所以说,只有在service因异常而断开连接的时候,这个方法才会用到

其他

由于Service 的onStart()方法只有在startService()启动Service的情况下才调用,故使用onStart()的时候要注意这点。

与 Service 通信并且让它持续运行

      如果我们想保持和 Service 的通信,又不想让 Service 随着 Activity 退出而退出呢?你可以先 startService() 然后再 bindService() 。

当你不需要绑定的时候就执行 unbindService() 方法,执行这个方法只会触发 Service 的 onUnbind() 而不会把这个 Service 销毁。

这样就可以既保持和 Service 的通信,也不会随着 Activity 销毁而销毁了。


*************************************************************

再说下bindService于绑定者之间的调用关系:

由于Android 中的Service使用了onBind 的方法去绑定服务,返回一个Ibinder对象进行操作(Ibinder对象是onServiceConnected的参数,

一般在这里获得Ibinder),而我们要获取具体的Service方法的内容的时候,我们需要Ibinder对象返回具体的Service对象才能操作,

所以说具体的Service对象必须首先实现Binder对象,这个样子的话我们才能利用bindService的方法对Service进行绑定,

获取Binder对象之后获取具体的Service对象,然后才获取Service中的方法等等。所以我们需要注意的是bindService的

方式去绑定服务获取的必定是实现了Binder的对象,所以这是我们必须使用Binder的方式去获取Service的方式而不是

直接使用Service的类,这个是Android内部实现所约束的。

方法过程如下:

Intent intent = new Intent(MainActivity.this,BindService.class)->新建了BindService对象->新建了MyBinder对象

->bindService(intent, conn, Context.BIND_AUTO_CREATE);->onBind()函数  -----传递MyBinder对象------->onServiceConnected()

 --> 通过传递的Binder对象获取刚刚和Binder对象对应的BindService 对象  -->调用Service中定义的方法。

    这个其中必须通过Binder对象,因为是通过Binder对象来传递的,通过Binder对象获取Service对象,然后获取所需的服务,

所以Service必须实现Binder,以便传递和使用。


好了,说到这基本也把Service的基本用法搞定了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值