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); //绑定后自动创建