实现方式
目前比较常规的做法是:开启前台 service 提高存活优先级
在 AndroidManifest.xml 中配置权限和 service 注册:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<service android:name=".CallService" android:enabled="true" android:exported="false" />
实现前台 service:
参考TRTC 官网 demo 实现:https://github.com/tencentyun/LiteAVProfessional_Android
public class CallService extends Service {
private static final int NOTIFICATION_ID = 1001;
private static CallService instance = null;
@Override
public void onCreate() {
super.onCreate();
instance = this;
Notification notification = createForegroundNotification();
startForeground(NOTIFICATION_ID, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
public static void start(Context context) {
if (isServiceRunning(context , CallService.class.getName())) {
return;
}
Intent service = new Intent(context, CallService.class);
if (Build.VERSION.SDK_INT >= 28) {
context.startForegroundService(service);
}
}
public static void stop() {
if (instance != null) {
instance.stopForeground(true);
instance.stopSelf();
}
}
private Notification createForegroundNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String notificationChannelId = "notification_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "TRTC Foreground Service Notification";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
notificationChannel.setDescription("Channel description");
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(getString(R.string.app_name));
builder.setContentText(getString(R.string.working));
builder.setWhen(System.currentTimeMillis());
return builder.build();
}
public static boolean isServiceRunning(Context context , final String className) {
ActivityManager am =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> info = am.getRunningServices(0x7FFFFFFF);
if (info == null || info.size() == 0) return false;
for (ActivityManager.RunningServiceInfo aInfo : info) {
if (className.equals(aInfo.service.getClassName())) return true;
}
return false;
}
}
使用方式:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CallService.start(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
CallService.stop();
}
}
|