前言
- Service作为Android四大组件之一,应用非常广泛
- 本文将介绍对Service进行全面介绍(基础认识、生命周期、使用和应用场景)
目录
1. 基础知识
- 定义:服务,属于Android中的计算型组件
- 作用:提供需要在后台长期运行的服务(如复杂计算、下载等等)
- 特点:长生命周期的、没有用户界面、在后台运行
2. 生命周期方法详解
3. Service分类
3.1 Service的类型
分类
3.2 详细介绍
Service类型的详细介绍
4. Service的使用解析
由上述可知,服务Service总共分为:
分类
接下来,我将介绍每种Service的具体使用,具体请看我写的文章:Android:(本地、可通信的、前台、远程)Service使用全面介绍
5. 使用场景
- 通过上述描述,你应该对Service类型及其使用非常了解;
- 那么,我们该什么时候用哪种类型的Service呢?
- 各种Service的使用场景请看下图:
使用场景
6. 其他思考
6.1 Service和Thread的区别
- 结论:Service和Thread之间没有任何关系
- 之所以有不少人会把它们联系起来,主要因为Service的后台概念
后台的定义:后台任务运行完全不依赖UI,即使Activity被销毁,或者程序被关闭,只要进程还在,后台任务就可以继续运行
- 其实二者存在较大的区别,如下图:
Paste_Image.png
一般来说,会将Service和Thread联合着用,即在Service中再创建一个子线程(工作线程)去处理耗时操作逻辑,如下代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//新建工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 开始执行后台任务
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
class MyBinder extends Binder {
public void service_connect_Activity() {
//新建工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 执行具体的下载任务
}
}).start();
}
}
1. 生命周期常用方法
在Service的生命周期里,常用的有:
- 4个手动调用的方法
手动调用方法 | 作用 |
startService() | 启动服务 |
stopService() | 关闭服务 |
bindService() | 绑定服务 |
unbindService() | 解绑服务 |
- 5个内部自动调用的方法
内部自动调用的方法 | 作用 |
onCreat() | 创建服务 |
onStartCommand() | 开始服务 |
onDestroy() | 销毁服务 |
onBind() | 绑定服务 |
onUnbind() | 解绑服务 |
2. 生命周期方法具体介绍
主要介绍内部调用方法和外部调用方法的关系。
2.1 startService()
- 作用:启动Service服务
- 手动调用startService()后,自动调用内部方法:onCreate()、onStartCommand()
- 调用逻辑如下:
调用逻辑
2.2 stopService()
- 作用:关闭Service服务
- 手动调用stopService()后,自动调用内部方法:onDestory()
- 调用的逻辑:
调用逻辑
2.3 bindService()
- 作用:绑定Service服务
- 手动调用bindService()后,自动调用内部方法:onCreate()、onBind()
- 调用的逻辑:
调用的逻辑
2.4 unbindService()
- 作用:解绑Service服务
- 手动调用unbindService()后,自动调用内部方法:onCreate()、onBind()、onDestory()
- 调用的逻辑:
调用的逻辑
3. 常见的生命周期使用
3.1 只使用startService启动服务的生命周期
startService启动服务的生命周期
3.2 只使用BindService绑定服务的生命周期
BindService绑定服务的生命周期
3.3 同时使用startService()启动服务、BindService()绑定服务的生命周期
Paste_Image.png
3.4 特别注意
- startService()和stopService()只能开启和关闭Service,无法操作Service;
bindService()和unbindService()可以操作Service
- startService开启的Service,调用者退出后Service仍然存在;
BindService开启的Service,调用者退出后,Service随着调用者销毁。
demo1:
MyService
package com.glsite.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
/**
* @author glsite.com
* @version $Rev$
* @des ${TODO}
* @updateAuthor $Author$
* @updateDes ${TODO}
*/
public class MyService extends Service {
private IBinder mBinder = new MyBinder();
public MyService() {
System.out.println("MyService constructor");
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy");
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("onUnbind");
return super.onUnbind(intent);
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
public void execute() {
System.out.println("通过Binder得到Server的引用来调用Service内部的方法");
}
}
MainActivity
package com.glsite.servicedemo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private Intent mIntent;
private ServiceConnection mConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ((MyService.MyBinder) service).getService();
System.out.println("service连接成功");
mService.execute();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
private MyService mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIntent = new Intent(this, MyService.class);
// startService(mIntent);
bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stop(View view) {
if (mIntent != null) {
stopService(mIntent);
}
}
public void unbind(View view) {
unbindService(mConnection);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
}
}
demo2:
GovService
package com.glsite.bindservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class GovService extends Service {
public GovService() {
}
private class MyBinder extends Binder implements IService{
@Override
public void callBanZheng(int money) {
if (money > 200) {
kaiGeZhengMing();
} else {
Toast.makeText(getApplicationContext(),"我不是那样的人~~~,你妈妈喊你回家吃饭", Toast.LENGTH_SHORT).show();
}
}
@Override
public void 去旅游() {
System.out.println("一起去岛国旅游,你懂的...");
}
public void 打麻将() {
Toast.makeText(getApplicationContext(),"我们一起打麻将", Toast.LENGTH_SHORT).show();
}
public void 洗桑拿() {
Toast.makeText(getApplicationContext(),"我们一起洗桑拿", Toast.LENGTH_SHORT).show();
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new MyBinder();
}
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("onDestroy");
super.onDestroy();
}
public void kaiGeZhengMing() {
Toast.makeText(this,"经过证明,你没有房产", Toast.LENGTH_SHORT).show();
}
}
IService
package com.glsite.bindservice;
/**
* @author glsite.com
* @version $Rev$
* @des ${TODO}
* @updateAuthor $Author$
* @updateDes ${TODO}
*/
public interface IService {
public void callBanZheng(int money);
public void 去旅游();
}
MainActivity
package com.glsite.bindservice;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private IService mIService;
private MyConn mConn;
private class MyConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mIService = (IService) service;
System.out.println("屁民联系上了贪官的小三");
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("因为做的太过分了,已经失去了她");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 绑定服务,调用服务里面的方法
*
* @param view
*/
public void bind(View view) {
Intent intent = new Intent(this, GovService.class);
mConn = new MyConn();
bindService(intent, mConn, BIND_AUTO_CREATE);
}
/**
* 解绑服务,调用服务里面的方法
*
* @param view
*/
public void unbind(View view) {
if (mConn != null) {
unbindService(mConn);
mIService = null;
mConn = null;
}
}
/**
* 调用服务,调用服务里面的方法
*
* @param view
*/
public void call(View view) {
if (mIService != null) {
mIService.callBanZheng(10000);
mIService.去旅游();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.glsite.bindservice">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service
android:name=".GovService"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>