gpt4 book ai didi

android - 当用户点击来自锁屏的通知时启动 Activity

转载 作者:行者123 更新时间:2023-11-29 14:16:51 28 4
gpt4 key购买 nike

我希望能够在设备锁定时点击通知并在不解锁设备的情况下启动 Activity 。

我在 onCreate() 方法中为 Activity 添加了一些标志,允许在设备锁定时显示 Activity :

Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

这是创建通知的代码:

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);

Notification notification = new Notification.Builder(this)
.setContentIntent(pendingIntent)
.setContentTitle("Title")
.setSmallIcon(android.R.drawable.ic_menu_more)
.build();

NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(1, notification);

我还在 list 中添加了 showOnLockScreen="true":

<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:showOnLockScreen="true"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

有效的东西:

  • Activity 在设备锁定时显示(例如,如果我将 Activity 留在前台并锁定手机, Activity 将保持在前台而不需要解锁手机)
  • 如果我在手机锁定时点击通知,它会要求我解锁,然后显示 Activity

我希望能够在不解锁设备的情况下执行相同的操作。
我错过了什么?

最佳答案

试试这个!!!

private NotificationCompat.Builder mBuilder;

Intent notifyIntent = new Intent(getApplicationContext(), MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notifyIntent, 0);
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setContent(remoteViews)
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setOngoing(true);

这是在设备 5.0 及更低版本上获取通知图标的方法

private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.notification_icon : R.mipmap.ic_launcher;
}

删除onCreate下面的代码

Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

关于android - 当用户点击来自锁屏的通知时启动 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37245288/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com