Android 10 上的 BroadcastReceiver 无法启动活动

问题描述 投票:0回答:3

我昨晚更新了我的操作系统版本到android 10,从那以后广播接收器中的startActivity函数什么都不做。这是我尝试根据 CommonsWare 的回答开始活动的方式:

Intent i = new Intent(context, AlarmNotificationActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // This is at least android 10...

                Log.d("Debug", "This is android 10");
                // Start the alert via full-screen intent.
                PendingIntent startAlarmPendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
                String CHANNEL_ID = "my_channel_02";
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                        context.getString(R.string.notification_channel_name_second),
                        NotificationManager.IMPORTANCE_HIGH);
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.createNotificationChannel(channel);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                        .setContentTitle("Um, hi!")
                        .setAutoCancel(true)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setFullScreenIntent(startAlarmPendingIntent, true);
                Log.d("Debug", "Try to load screen");
                notificationManager.notify(0, builder.build());

            }

日志显示我正在执行通知命令,但没有任何反应。我正在请求对清单的 USE_FULL_SCREEN_INTENT 权限,以便我应该能够使用全屏意图。 由于那个问题,我的应用程序现在没用了。有谁知道如何解决它?

android broadcastreceiver android-pendingintent start-activity android-10.0
3个回答
13
投票

Android 10 对后台活动启动的限制大约在六个月前宣布。您可以在文档中阅读更多相关信息。

改为使用高优先级通知,并关联全屏

Intent
。请参阅文档此示例应用程序 通过使用
WorkManager
触发需要提醒用户的后台事件来演示这一点。在那里,我使用高优先级通知而不是直接启动活动:

val pi = PendingIntent.getActivity(
  appContext,
  0,
  Intent(appContext, MainActivity::class.java),
  PendingIntent.FLAG_UPDATE_CURRENT
)

val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
  .setSmallIcon(R.drawable.ic_notification)
  .setContentTitle("Um, hi!")
  .setAutoCancel(true)
  .setPriority(NotificationCompat.PRIORITY_HIGH)
  .setFullScreenIntent(pi, true)

val mgr = appContext.getSystemService(NotificationManager::class.java)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
  && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
  mgr.createNotificationChannel(
    NotificationChannel(
      CHANNEL_WHATEVER,
      "Whatever",
      NotificationManager.IMPORTANCE_HIGH
    )
  )
}

mgr.notify(NOTIF_ID, builder.build())

10
投票

Android 10可以使用SYSTEM_ALERT_WINDOW强制启动活动窗口,参考这个设置superposition setting

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>  
</activity>  
    <receiver
        android:name=".OnBootReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

在启动的应用程序中检查权限:

private void RequestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + this.getPackageName()));
            startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
        } else {
            //Permission Granted-System will work
        }
    }
}

您可以将用户意图作为 android 旧版本

public class OnBootReceiver extends BroadcastReceiver {
    private static final String TAG = OnBootReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Intent activity = new Intent(context, MainActivity.class);
            activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(activity);
        } catch (Exception e){
            Log.d(TAG,e.getMessage()+"");
        }
    }
}

2
投票

Android 10 对后台活动启动的限制大约在六个月前宣布。您可以在文档中阅读更多相关信息。

所以你需要有一个高级通知,当用户点击通知时,你的活动将被打开通知

public class UIExampleReceiver extends BroadcastReceiver {

    public static final String TAG_NOTIFICATION = "NOTIFICATION_MESSAGE";
    public static final String CHANNEL_ID = "channel_1111";
    public static final int NOTIFICATION_ID = 111111;
    private static final String TAG = "Receiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            // If android 10 or higher
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                startActivityNotification(
                    context,
                    NOTIFICATION_ID,
                    context.getResources().getString(R.string.open_app),
                    context.getResources().getString(R.string.click_app)
                );
            } else {
                // If lower than Android 10, we use the normal method ever.
                Intent activity = new Intent(context, ExampleActivity.class);
                activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(activity);
            }
        } catch (Exception e) {
            Log.d(TAG, e.getMessage() + "");
        }
    }


    // notification method to support opening activities on Android 10
    public static void startActivityNotification (Context context, int notificationID,
    String title, String message) {

        NotificationManager mNotificationManager =
        (NotificationManager)
        context.getSystemService(Context.NOTIFICATION_SERVICE);
        //Create GPSNotification builder
        NotificationCompat.Builder mBuilder;

        //Initialise ContentIntent
        Intent ContentIntent = new Intent(context, ExampleActivity.class);
        ContentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
        Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent ContentPendingIntent = PendingIntent . getActivity (context,
        0,
        ContentIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder = new NotificationCompat . Builder (context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(message)
            .setColor(context.getResources().getColor(R.color.colorPrimaryDark))
            .setAutoCancel(true)
            .setContentIntent(ContentPendingIntent)
            .setDefaults(Notification.DEFAULT_LIGHTS | Notification . DEFAULT_VIBRATE)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                CHANNEL_ID,
                "Activity Opening Notification",
                NotificationManager.IMPORTANCE_HIGH
            );
            mChannel.enableLights(true);
            mChannel.enableVibration(true);
            mChannel.setDescription("Activity opening notification");

            mBuilder.setChannelId(CHANNEL_ID);

            Objects.requireNonNull(mNotificationManager).createNotificationChannel(mChannel);
        }
        Objects.requireNonNull(mNotificationManager).notify(
            TAG_NOTIFICATION, notificationID,
            mBuilder.build()
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.