2017-03-23 74 views
-1

我想在用戶收到應用程序通知時自動啓動應用程序,在啓動器圖標上不會有點擊操作。如何在收到通知[FCM]時自動啓動android應用程序?

+0

[看這裏](http://stackoverflow.com/a/30090042/681929) – nobalG

+0

不工作我檢查了這個 –

+0

哥們跟着這個https://answers.madewithmarmalade.com/questions/16205/launch-application- from-notification-android-edk.html –

回答

1

在您的onMessageReceived()方法中,您可以嘗試添加您的startActivity(intent)代碼。這樣,當應用程序收到FCM消息時,它會啓動應用程序。像這樣...

@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 
    // Check if message contains a notification payload. 
    if (remoteMessage.getNotification() != null) { 
     startActivity(new Intent(this, MainActivity.class)); 
    } 
} 
+0

從Activity上下文外部調用startActivity()需要FLAG_ACTIVITY_NEW_TASK標誌。得到這個錯誤 –

+0

onMessageReceived不會調用時,應用程序是背景所以這將反正不幫我 –

+0

感謝您的回覆人甚至你的線程也是我的解決方案的一部分:) –

1

方法onMessageReceived()正常工作時,應用程序在後臺,如果通知正文不包含「通知」參數。所有數據都應粘貼在「數據」中。像這樣:

{ 
    "to":"token", 
    "priority":"high", 
    "data": { 
     "title": "Carmen", 
     "text": "Популярные новости за сегодня!", 
     etc.. 
    } 
} 

然後你可以在你的代碼中解析它,並在通知中顯示標題和文本。

例如:

override fun onMessageReceived(remoteMessage: RemoteMessage?) { 
     Log.d("FirebaseService", "Receive notification: ${remoteMessage?.data}") 
     remoteMessage?.let { showNotification(remoteMessage) } 
    } 

    private fun showNotification(remoteMessage: RemoteMessage) { 
     val notificationModel: NotificationModel 
       = getNotificationModelFromMessageData(remoteMessage.data) 

     val intent = Intent(this, SplashActivity::class.java) 
     intent.putExtra(NOTIFICATION_ARGUMENT, notificationModel) 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) 

     val pendingIntent = PendingIntent.getActivity(
       this, NOTIFICATION_RECEIVE_REQUEST_CODE, 
       intent, PendingIntent.FLAG_ONE_SHOT) 

     val defaultNotificationSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) 
     val notification: Notification 
       = NotificationCompat.Builder(this) 
       .setAutoCancel(true) 
       .setContentIntent(pendingIntent) 
       .setContentTitle(notificationModel.title) 
       .setContentText(notificationModel.text) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setSound(defaultNotificationSound) 
       .build() 

     val notificationManager: NotificationManager 
       = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 
     notificationManager.notify(NOTIFICATION_ID, notification) 
    } 

    private fun getNotificationModelFromMessageData(jsonData: MutableMap<String, String>): NotificationModel { 
     return NotificationModel(
       jsonData[TITLE_PARAMETER] as String, 
       jsonData[TEXT_PARAMETER] as String, 
       jsonData[DAYS_PARAMETER] as String, 
       jsonData[MESSAGE_ID] as String) 
    } 

希望它能幫助!

+0

感謝您的答覆我從FCM數據像這樣{ Key = value}在onMessageReceived中如何實現你顯示的JSON格式.. –

+0

最後我解決了我的問題謝謝這是因爲我沒有使用任何REST客戶端,所以數據格式是{key = value}當應用程序在前臺工作 –

相關問題