Android學習(八)Service服務
Service
服務是一個不提供用戶界面,可以長時間在後臺運行的應用程序組件。例如,一項服務可以在後臺處理網絡事務,播放音樂,執行文件I / O或與內容提供者進行交互。
基礎
創建Service
這是所有服務的基類。擴展此類時,重要的是創建一個新線程,服務可以在其中完成所有工作。該服務默認情況下使用應用程序的主線程,這可能會降低應用程序正在運行的任何活動的性能。
如果需要使用子線程開發,可以參考Android學習(七)Android多線程初學。
- 創建一個類繼承Service。
通常我們重寫onCreate()、onStartCommand()和onDestroy()方法。
package com.example.testapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class TestService extends Service {
private static final String TAG = "TestService";
public TestService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
}
方法名 | 用途 |
---|---|
onCreate() | 服務首次啓動時,執行一次。重複啓動,不再執行。 |
onStartCommand() | 每次啓動服務,都會執行一次。 |
onDestroy() | 服務銷燬時,執行一次。 |
- 在AndroidManifest.xml中註冊service
<service
android:name=".TestService"
android:enabled="true"
android:exported="true" />
啓動和停止Service
和啓動activity類似,也是藉助Intent來實現。
- 啓動服務
Intent intent = new Intent(this, TestService.class);
startService(intent);
- 停止服務
通過Context類來停止服務
Intent stopIntent = new Intent(this, TestService.class);
stopService(stopIntent);
通過在service內部調用stopSelf()
stopSelf();
創建IntentService
這是一個子類,它使用子線程一次處理所有請求後,會自動停止。如果不需要服務同時處理多個請求,那麼這是最佳選擇。
- 創建一個類繼承IntentService
在onHandleIntent()方法中,執行耗時操作。
啓動IntentService
和啓動普通Service一樣
Intent intentService = new Intent(this, TestIntentService.class);
startService(intentService);
綁定服務
當啓動好服務後,活動需要和服務進行比較密切通信時,我們可以綁定服務來實現通信。
服務準備
- 在服務中創建一個對象並繼承Binder
private TestBinder binder = new TestBinder();
class TestBinder extends Binder {
public void Test() {
Log.d(TAG, "TestBinder Test");
}
}
- 在onBind()方法中返回創建對象
@Override
public IBinder onBind(Intent intent) {
return binder;
}
活動準備
- 創建一個ServiceConnection對象
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (TestService.TestBinder) service; //得到實例
binder.Test(); //調用定義方法
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
- 綁定服務
Intent bindService = new Intent(this, TestService.class);
bindService(bindService, connection, BIND_AUTO_CREATE); //綁定後自動創建
- 解綁服務
unbindService(connection); //解綁
前臺服務
前臺服務執行一些用戶注意的操作。前臺服務必須顯示Notification。即使用戶未與應用程序進行交互,前臺服務也將繼續運行。
注意:以Android 9(API級別28)或更高版本爲目標並且使用前臺服務的應用必須請求 FOREGROUND_SERVICE 權限。
- 在服務中調用startForeground()方法
主要是在onCreate()方法中,創建Notification對象,再調用startForeground()方法
package com.example.testapplication;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class TestForegroundService extends Service {
public TestForegroundService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, getPackageName())
.setContentTitle("test title")
.setContentText("test text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher))
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
}
- 啓動服務
Intent bindService = new Intent(this, TestForegroundService.class);
startService(bindService); //綁定後自動創建