当用户点击来自锁定屏幕的通知时启动活动

问题描述:

我希望能够在设备锁定时点击通知,并在未解锁设备的情况下启动活动。当用户点击来自锁定屏幕的通知时启动活动

我添加一些标志到活动中的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> 

件事情是工作:

  • 当设备被锁定的活性显示(例如,如果我留在前台活动并锁定手机的活动仍然对前景无需解锁手机)
  • 如果我点击的通知时,手机被锁定,要求我先解锁,然后活动显示

我希望能够做同样的,但没有解锁设备。
我错过了什么?

试试这个!

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); 
+0

的'remoteViews'变量未声明(也不分配)。 – pomber

+0

我试了其余的设置,并没有解决我的问题。您确定此代码是否允许通过锁定屏幕上的通知启动活动而无需解锁设备? – pomber

+0

我确定。它非常适合我的应用程序! –