android開發筆記 (三)Service的簡單使用

1 基礎認知

1.1 Service 是什麼?

Service是一個應用組件, 它用來在後臺完成一個時間跨度比較大的工作且沒有關聯任何界面。

1.2 Service所做工作舉例

  • 訪問網絡
  • 播放音樂
  • 文件IO操作
  • 大量數據的數據庫操作
  • 其他

1.3 Service的特點

  • Service在後臺運行,不與用戶直接交互
  • 即使退出應用,服務也不會立即停止
  • 在默認情況下,Service運行在應用程序進程的主線程中(也就是UI線程),如果需要在Service中處理一些如網絡連接這種耗時任務,那麼應該將這些任務放在工作線程中,避免阻塞用戶界面

1.4 Service的分類

  1. Local Service(本地服務):Service對象與Serive的啓動者在同個進程中運行, 兩者的通信是進程內通信
  2. Remote Service(遠程服務):Service對象與Service的啓動者不在同一個進程中運行, 這時存在一個進程間通信的問題, Android專門爲此設計了AIDL來實現進程間通信

2 啓動與停止服務

2.1 啓動方式

2.1.1 代碼示例

佈局文件代碼:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/start_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="112dp"
        android:layout_marginLeft="112dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="啓動服務"
        app:layout_constraintEnd_toStartOf="@+id/stop_service"
        app:layout_constraintHorizontal_bias="0.018"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/bind_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="綁定服務"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.345"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/start_service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="停止服務"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="解綁服務"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/bind_service"
        app:layout_constraintTop_toBottomOf="@+id/stop_service" />

</androidx.constraintlayout.widget.ConstraintLayout>

清單文件代碼:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicepractice">

    <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">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyService"/>
    </application>

</manifest>

activity代碼:

package com.example.servicepractice;

import androidx.appcompat.app.AppCompatActivity;

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 android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;
    private boolean isBind;
    private Intent intent;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG, "onServiceConnected: ");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "onServiceDisconnected: ");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this, MyService.class);
        initViews();
    }

    private void initViews() {
        startService = findViewById(R.id.start_service);
        stopService = findViewById(R.id.stop_service);
        bindService = findViewById(R.id.bind_service);
        unbindService = findViewById(R.id.unbind_service);
        startService.setOnClickListener(onClickListener);
        stopService.setOnClickListener(onClickListener);
        bindService.setOnClickListener(onClickListener);
        unbindService.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.start_service:
                    startService(intent);
                    break;
                case R.id.stop_service:
                    stopService(intent);
                    break;
                case R.id.bind_service:
                    if (!isBind) {
                        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                        isBind = true;
                        Toast.makeText(MainActivity.this, "綁定成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,
                                "已經綁定成功,不需要再次綁定",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.unbind_service:
                    if (isBind) {

                        isBind = false;
                        Toast.makeText(MainActivity.this, "解綁完成",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "已經解綁,不需要再次解綁",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (isBind) {
            unbindService(serviceConnection);
            isBind = false;
        }
        super.onDestroy();
    }
}

service中的代碼:

package com.example.servicepractice;

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

public class MyService extends Service {
    private static final String TAG = MyService.class.getSimpleName();


    public MyService() {
        Log.e(TAG, "MyService: " );
    }

    @androidx.annotation.Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: ");
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate: ");
        super.onCreate();
    }

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

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: ");
        super.onDestroy();
    }

    class MyBinder extends Binder {
        public MyBinder() {
            Log.e(TAG, "MyBinder: ");
        }
    }
}

2.1.2 一般啓動

  • context.startService(Intent intent)
  • context.stopService(Intent intent)

點擊開始服務

MyService: MyService: 
MyService: onCreate: 
MyService: onStartCommand: 

當service已經啓動後再次調用startService(Intent intent),將不會再去創建service,而是調用onStartCommand()回調方法,也就是說Service的構造方法和onCreate()回調方法將不再調用。

onStartCommand: 

點擊停止服務

MyService: onDestroy: 

 

2.1.3 綁定啓動與解綁

  • context.bindService(Intent intent, ServiceConnection connection)
  • context.unbindService(ServiceConnection connection)

點擊綁定服務 , 綁定服務過後再次調用bindService()不會調用任何回調方法

MyService: MyService: 
MyService: onCreate: 
MyService: onBind: 
MyService: MyBinder: 
MainActivity: onServiceConnected: 

點擊解綁服務

MyService: onUnbind: 
MyService: onDestroy: 

如果綁定過後沒有解綁就銷燬activity,則會報如下錯誤

E/ActivityThread: Activity com.example.servicepractice.MainActivity has leaked ServiceConnection com.example.servicepractice.MainActivity$1@3b1444 that was originally bound here
    android.app.ServiceConnectionLeaked: Activity com.example.servicepractice.MainActivity has leaked ServiceConnection com.example.servicepractice.MainActivity$1@3b1444 that was originally bound here
        at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1610)
        at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1502)
        at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1659)
        at android.app.ContextImpl.bindService(ContextImpl.java:1612)
        at android.content.ContextWrapper.bindService(ContextWrapper.java:698)
        at com.example.servicepractice.MainActivity$2.onClick(MainActivity.java:67)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

2.1.3 Service的生命週期圖

從上面這張圖片可以看出,一個Service可以和多個組件綁定,並且只有當所有的組件都解綁之後纔會調用onUnbind()。、

3 AIDL

3.1 基礎認知

  • 每個應用程序都運行在自己的獨立進程中,並且可以啓動另一個應用進程的服務,而且經常需要在不同的進程間傳遞數據對象。
  • 在Android平臺,一個進程不能直接訪問另一個進程的內存空間,所以要想對話,需要將對象分解成操作系統可以理解的基本單元,並且有序的通過進程邊界。
  • AIDL (Android Interface Definition Language) 用於生成可以在Android設備上兩個進程之間進行進程間通信(interprocess communication, IPC)的代碼。
  • 如果在一個進程中(例如Activity)要調用另一個進程中(例如Service)對象的操作,就可以使用AIDL生成可序列化的參數。

3.2 編寫aidl注意事項

  1. 接口名和aidl文件名必須相同
  2. 接口和方法前不能加訪問權限修飾符(public, private, protected等),也不能用final,static
  3. Aidl默認支持類型包括java基本類型和String,List,Map,CharSequence,使用這些類型時不需要import聲明。對於List和Map中的元素類型必須是aidl支持的類型,如果使用自定義類型作爲參數或者返回值,自定義類型必須實現Parcelable接口。
  4. 自定義類型和aidl生成的其他接口類型在aidl描述文件中,應該顯示import,即便該類和aidl文件在同一個包中。
  5. 自定義類型的aidl文件名要和自定義類的名字相同,如Book.java,Book.aidl
  6. aidl文件和自定義實體類在服務端和客戶端都要有一套一樣的,包名也要一樣
  7. 在aidl文件中所有非java基本類型參數必須加上in, out , inout標記,以指明參數是輸入參數、輸出參數還是輸入輸出參數。
  8. java 原始類型默認的標記爲in,不能爲其他標記。

3.3 遠程服務端代碼

清單文件代碼:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.remoteservice">

    <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">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".remote.MyRemoteService">
            <intent-filter>
                <action android:name="android.intent.action.test"/>
            </intent-filter>
        </service>
    </application>

</manifest>

實體數據類:

package com.example.remoteservice.remote;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class Student implements Parcelable {
    private int id;
    private String name;
    private int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    protected Student(Parcel in) {
        id = in.readInt();
        name = in.readString();
        age = in.readInt();
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            Log.e("TAG", "createFromParcel: ");
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        Log.e("TAG", "writeToParcel: ");
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeInt(age);
    }
}

遠程Service代碼:

package com.example.remoteservice.remote;

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

public class MyRemoteService extends Service {
    @androidx.annotation.Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("TAG", "onBind()");
        return new StudentService();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("TAG", "onUnbind()");
        return super.onUnbind(intent);
    }

    //處理Student相關的業務邏輯類
    class StudentService extends IStudentService.Stub {

        @Override
        public Student getStudentById(int id) {
            Log.e("TAG", "Service getStudentById() "+id);
            return new Student(id, "Tom", 80);
        }
    }
}

Service aidl接口文件:

// IStudentService.aidl
package com.example.remoteservice.remote;
import com.example.remoteservice.remote.Student;

// Declare any non-default types here with import statements

interface IStudentService {
    Student getStudentById(int id);
}

實體類的aidl文件:

// Student.aidl
package com.example.remoteservice.remote;
parcelable Student;

文件結構圖:

3.4 客戶端代碼:

清單文件代碼:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicepractice">

    <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">
        <activity android:name=".MainActivity">

        </activity>

        <activity android:name=".client.ClientActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyService"/>
    </application>

</manifest>

xml文件代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="bindRemoteService"
        android:text="bind remote Service" />

    <EditText
        android:id="@+id/et_aidl_id"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="學員ID"
        android:text="3" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="invokeRemote"
        android:text="調用遠程服務端的方法" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="unbindRemoteService"
        android:text="unbind remote Service" />
</LinearLayout>

activity代碼:

package com.example.servicepractice.client;

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.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.remoteservice.remote.IStudentService;
import com.example.remoteservice.remote.Student;
import com.example.servicepractice.R;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class ClientActivity extends AppCompatActivity {
    private EditText et_aidl_id;
    private ServiceConnection conn;
    private IStudentService studentService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        et_aidl_id = findViewById(R.id.et_aidl_id);
    }


    public void bindRemoteService(View v) {
        Intent intent = new Intent("android.intent.action.test");
        intent.setPackage("com.example.remoteservice");
        if (conn == null) {
            conn = new ServiceConnection() {

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }

                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Log.e("TAG", "onServiceConnected()");
                    studentService = IStudentService.Stub.asInterface(service);
                }
            };
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
            Toast.makeText(this, "綁定Service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已經綁定Service", Toast.LENGTH_SHORT).show();
        }
    }

    public void invokeRemote(View v) throws RemoteException {
        if (studentService != null) {
            int id = Integer.parseInt(et_aidl_id.getText().toString());
            Student student = studentService.getStudentById(id);
            Toast.makeText(this, student.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    public void unbindRemoteService(View v) {
        unbindRemoteService();
    }

    private void unbindRemoteService() {
        if (conn != null) {
            unbindService(conn);
            conn = null;
            studentService = null;
            Toast.makeText(this, "解綁Service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "還未綁定Service", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        unbindRemoteService();
        super.onDestroy();
    }
}

客戶端文件結構圖:

3.5 運行效果截圖

服務端日誌:

TAG: onBind()
TAG: Service getStudentById() 3
TAG: writeToParcel: 

客戶端日誌:

TAG: onServiceConnected()
TAG: createFromParcel: 

4 案例:播放音樂

xml代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="播放"/>

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暫停"/>

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止"/>

    <Button
        android:id="@+id/exit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="退出"/>
</LinearLayout>

activity代碼:

package com.example.servicepractice;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MusicAcitivity extends AppCompatActivity implements View.OnClickListener {
    private Button btnPlay;
    private Button btnPause;
    private Button btnStop;
    private Button btnExit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        initViews();
    }

    private void initViews() {
        btnPlay = findViewById(R.id.play);
        btnPause = findViewById(R.id.pause);
        btnStop = findViewById(R.id.stop);
        btnExit = findViewById(R.id.exit);
        btnPlay.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnExit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MusicService.class);
        switch (v.getId()) {
            case R.id.play:
                intent.putExtra("action", "play");
                break;
            case R.id.pause:
                intent.putExtra("action", "pause");
                break;
            case R.id.stop:
                intent.putExtra("action", "stop");
                break;
            case R.id.exit:
                intent.putExtra("action", "exit");
                finish();
                break;
        }
        startService(intent);
    }
}

service代碼:

package com.example.servicepractice;

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

import androidx.annotation.Nullable;

public class MusicService extends Service {
    private MediaPlayer mediaPlayer;

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


    private void playMedia() {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(this, R.raw.water_hander);
        }
        mediaPlayer.start();
    }

    private void pauseMedia() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    private void stopMedia() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();//停止
            mediaPlayer.reset();//重置
            mediaPlayer.release();//釋放資源
            mediaPlayer = null;//使對象爲空,否者重新播放會crash
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("TAG", "onStartCommand: ");
        String action = intent.getStringExtra("action");
        if (action.equals("play")) {
            playMedia();
        } else if (action.equals("pause")) {
            pauseMedia();
        } else if (action.equals("stop")) {
            stopMedia();
        } else if (action.equals("exit")) {
            stopMedia();
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章