我希望能够在设备锁定时点按通知并在不解锁设备的情况下启动活动。
我在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);
这是创建通知的代码:
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);
我还在清单中添加了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>
正在发挥作用的事情:
我希望能够在不解锁设备的情况下做同样的事情 我错过了什么?
答案 0 :(得分:-2)
试试这个!!!
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);