四大组件之Service

一、Service种类

1、按运行地点

(1)本地服务:开启者和服务在同一个应用程序中。本地服务是运行在主进程的Main线程上。主进程被杀死后,服务便会终止。

(2)远程服务:开启者和服务在不同的应用程序中。远程服务是运行在独立进程的Main线程上。Activity所在的进程被杀死后,服务也不会终止。

2、按开启方式

(1)context.startService,服务和开启者之间没有任何关系,开启者退出和结束,服务仍然存在。并且Activity无法访问服务里的数据。

(2)context.bindService,开启者退出或者结束,服务也会被终止。Activity能和服务进行通信。


二、Service和Thread的区别

那么我们为什么要用 Service 呢?其实这跟 android 的系统机制有关,我们先拿 Thread 来说。Thread 的运行是独立于 Activity 的,也就是说当一个 Activity 被 finish 之后,如果你没有主动停止 Thread 或者 Thread 里的 run 方法没有执行完毕的话,Thread 也会一直执行。因此这里会出现一个问题:当 Activity 被 finish 之后,你不再持有该 Thread 的引用。另一方面,你没有办法在不同的 Activity 中对同一 Thread 进行控制。

举个例子:如果你的 Thread 需要不停地隔一段时间就要连接服务器做某种同步的话,该 Thread 需要在 Activity 没有start的时候也在运行。这个时候当你 start 一个 Activity 就没有办法在该 Activity 里面控制之前创建的 Thread。因此你便需要创建并启动一个 Service ,在 Service 里面创建、运行并控制该 Thread,这样便解决了该问题(因为任何 Activity 都可以控制同一 Service,而系统也只会创建一个对应 Service 的实例)。


三、Android的进程分为5个等级(从高到低)

1、Foreground process 前台进程,用户正在玩的应用程序对应的进程
2、Visible process    可视进程,比如有一个正在玩的应用程序,它是透明的,那背景的应用程序
                      对应的进程就是可视进程
3、Service process    服务进程,有后台服务运行
4、Backgroud process  后台进程,按Home小退的进程
5、Empty process      空进程,按Back退出的进程,任务栈清空。最容易被系统杀死。


四、startService方式开启服务

<span style="font-size:18px;">//开启服务
				Intent intent = new Intent(MainActivity.this,
						StartService.class);
				startService(intent);</span>
<span style="font-size:18px;">//停止服务
Intent intent = new Intent(MainActivity.this,StartService.class);
stopService(intent);
</span>
服务的生命周期:onCreate-->onStartCommand-->onDestory,服务被创建后,只要没有停止或者杀死,多次开启不会执行onCreate,只会执行onStartCommand


五、bindService方式开启服务

1、开启服务

<span style="font-size:18px;">//绑定方式开启服务
				Intent intent = new Intent(MainActivity.this, MyService.class);
				myConnection = new MyConnection();
				//BIND_AUTO_CREATE 服务不存在就会被创建
				bindService(intent, myConnection, BIND_AUTO_CREATE);</span>

2、Service类

public class MyService extends Service {
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("DBXStore", "服务被创建");
	}

	//返回IBinder对象实例
	@Override
	public IBinder onBind(Intent intent) {
		Log.i("DBXStore", "服务被绑定");
		return new MyBinder();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.i("DBXStore", "服务被解绑");
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("DBXStore", "服务结束");
	}

	private class MyBinder extends Binder implements IBinderInterface{
		
		//对外只暴露了该方法
		@Override
		public void show() {
			Toast.makeText(MyService.this, "绑定显示", Toast.LENGTH_SHORT).show();
		}
		
		//该方法没有暴露
		public void test(){
			
		}
	}
}

3、IBinderInterface接口

<span style="font-size:18px;">public interface IBinderInterface {
	/**
	 * 对外只暴露了show方法
	 */
	public void show();
}</span>

4、服务回调

<span style="font-size:18px;">/**
	 * 服务回调接口
	 * @author Administrator
	 *
	 */
	private class MyConnection implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			myBinder = (MyBinder) service;
			myBinder.show();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
	}</span>
5、停止服务,一般放在Activity的onDestory方法

<span style="font-size:18px;">// 绑定方式停止服务
				if (myConnection != null) {
					unbindService(myConnection);
					myBinder = null;
				}</span>

6、生命周期:onCreate-->onBind-->onUnbind-->onDestory


六、开启远程服务

1、远程服务

MyService类

<span style="font-size:18px;">public class MyService extends Service {

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

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	private class MyBinder extends IBinderInterface.Stub {

		@Override
		public void show(){
			Log.i("DBXStore", "远程服务被调用...");
		}

	}

}</span>
IBinderInterface.aidl

<span style="font-size:18px;">package com.example.remoteservice;

interface IBinderInterface {
	void show();
}
</span>


Manifest.xml文件

隐式意图访问:

<span style="font-size:18px;"> <service android:name="com.example.remoteservice.MyService" >
            <intent-filter >
                <action android:name="com.remoteservice" />
            </intent-filter>
        </service></span>

2、远程调用者

把远程服务的aidl文件复制过来,带上所在的包


public class MainActivity extends Activity {
	private Button start, call;
	private MyConnection serviceConnection;
	private IBinderInterface iBinderInterface;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		start = (Button) findViewById(R.id.start);
		call = (Button) findViewById(R.id.call);
		start.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//开启服务
				Intent intent = new Intent();
				intent.setAction("com.remoteservice");
				serviceConnection = new MyConnection();
				bindService(intent, serviceConnection, BIND_AUTO_CREATE);
			}
		});
		call.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//调用远程服务暴露的方法
				try {
					iBinderInterface.show();
				} catch (RemoteException e) {
					e.printStackTrace();
				} 
			}
		});
	}
	
	private class MyConnection implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i("DBXStore", "onServiceConnected");
			//获得IBinderInterface对象
			iBinderInterface = IBinderInterface.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(serviceConnection != null){
			unbindService(serviceConnection);
			iBinderInterface = null;
		}
	}
	
}

七、混合方式开启服务

1、startService:保证服务长期在后台运行

2、bindService:保证能调用服务里的方法

3、调用服务里的方法

4、unbindService:解除绑定

5、stopService:如果需要停止这个长期的服务,就调用该方法。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值