查看: 89|回覆: 0

[教程] 安卓14前端服务foregroundService权限问题解决办法

[複製鏈接]

4

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2009-10-26
發表於 2025-9-19 09:32:12 | 顯示全部樓層 |閲讀模式

发现问题

在安卓应用开发过程中,我们会使用到service,普通的service我们只需要在AndroidMainfest.xml文件中添加service类就好

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

前端服务foregroundService还需要添加

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

但如果只是这样,启动前端服务还是会报错

经查资料发现:

Android 14(API 34)对前台服务的权限体系进行了深度重构:

1.细分权限体系
除基础权限 FOREGROUND_SERVICE 外,必须根据服务类型声明对应的细分权限:

除基础权限 FOREGROUND_SERVICE 外,必须根据服务类型声明对应的细分权限:

  • 数据同步服务:FOREGROUND_SERVICE_DATA_SYNC
  • 位置服务:FOREGROUND_SERVICE_LOCATION
  • 媒体播放服务:FOREGROUND_SERVICE_MEDIA_PLAYBACK
  • 电话服务:FOREGROUND_SERVICE_PHONE_CALL

2.服务类型强校验

系统会严格验证 android:foregroundServiceType 属性与权限的匹配性,不匹配将抛出 SecurityException

java.lang.SecurityException: 
ForegroundServiceType dataSync requires android.permission.FOREGROUND_SERVICE_DATA_SYNC

3.通知权限前置要求

从 Android 13(API 33)开始,显示通知的前台服务必须动态请求 POST_NOTIFICATIONS 权限

解决方案

在AndroidMainfest.xml清单文件中这样添加:

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

    
    <application
        <service
            android:name=".service.MyForegroundService"
            android:enabled="true"
            android:exported="false"
            android:foregroundServiceType="dataSync">
        </service>

    </application>

Java代码中前端服务实现

  @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate:");
        Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "channel_id",
                    "通知",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            notificationManager.createNotificationChannel(channel);
        }

        //创建通知

        Notification notification = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.baseline_music_note_24)
                .setContentTitle("这是标题")
                .setContentText("这是内容")
                .build();
        startForeground(1, notification);
    }

运行如果发现通知栏中不存在,还需要进入设置->应用中打开app的通知权限

最后大家可以通过adb检查服务状态

adb shell dumpsys activity services | grep "ForegroundService"

总结 

到此这篇关于安卓14前端服务foregroundService权限问题解决办法的文章就介绍到这了,更多相关安卓14前端服务foregroundService权限内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!

回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部