Android 9.0 退后台保活


实现方式

目前比较常规的做法是:开启前台 service 提高存活优先级

在 AndroidManifest.xml 中配置权限和 service 注册:
<!-- 配置前台服务权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- 注册前台 service -->
<service android:name=".CallService" android:enabled="true" android:exported="false" />
实现前台 service:

参考TRTC 官网 demo 实现:https://github.com/tencentyun/LiteAVProfessional_Android

/**
 * 该 Service 用于应用保活,勿删
 *
 * 9.0 及之后的系统,应用退后台后摄像头和麦克风将停止工作(https://developer.android.com/about/versions/pie/android-9.0-changes-all)
 * 该 Service 是为了保证应用退后台摄像头和麦克风依旧可以正常工作。
 */
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);
        /*
         * 9.0 及之后的系统,应用退后台后摄像头和麦克风将停止工作(https://developer.android.com/about/versions/pie/android-9.0-changes-all)
         * 该 Service 是为了保证应用退后台摄像头和麦克风依旧可以正常工作,故仅在 9.0 及之后的系统启动。
         */
        if (Build.VERSION.SDK_INT >= 28) {
            context.startForegroundService(service);
        }
    }

    public static void stop() {
        if (Build.VERSION.SDK_INT >= 28) {
            if (instance != null) {
	            instance.stopForeground(true);
	            instance.stopSelf();
	            instance = null;
        	}
        }
    }

    private Notification createForegroundNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        String notificationChannelId = "notification_channel_id_01";
        // Android8.0以上的系统,新建消息通道
        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();
    }

    /**
     * Return whether service is running.
     *
     * @param className The name of class.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isServiceRunning(Context context , final String className) {
        ActivityManager am =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //noinspection ConstantConditions
        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);
        // 开启前台 service
        CallService.start(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束前台 service
        CallService.stop();
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值