1

通知でMainActivityではなくNotification.classアクティビティを開くようにします。私はコードを次のように変更しました:クリックすると通知アクティビティが開きますfirebaseの通知

Intent intent = new Intent(this, Notification.class); 

通知を受信して​​クリックすると、MainActivityが開きます。 私は多くの例を見てきましたが、MainActivityの代わりに別のアクティビティを取得するために変更する必要があるところに到達できませんでした。

通知は、ユーザーセグメントとしてfirebaseコンソールから送信されます。

import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.graphics.Color; 
import android.media.RingtoneManager; 
import android.net.Uri; 
import android.support.v4.app.NotificationCompat; 
import android.util.Log; 

import com.firebase.jobdispatcher.FirebaseJobDispatcher; 
import com.firebase.jobdispatcher.GooglePlayDriver; 
import com.firebase.jobdispatcher.Job; 
import com.google.firebase.messaging.FirebaseMessagingService; 
import com.google.firebase.messaging.RemoteMessage; 

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 

    /** 
    * Called when message is received. 
    * 
    * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. 
    */ 
    // [START receive_message] 
    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
       // TODO(developer): Handle FCM messages here. 
     Log.d(TAG, "From: " + remoteMessage.getFrom()); 

     // Check if message contains a data payload. 
     if (remoteMessage.getData().size() > 0) { 
      Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 

      if (/* Check if data needs to be processed by long running job */ true) { 
       // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher. 
       scheduleJob(); 
      } else { 
       // Handle message within 10 seconds 
       handleNow(); 
      } 

     } 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
     } 


    } 

    private void scheduleJob() { 
     // [START dispatch_job] 
     FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this)); 
     Job myJob = dispatcher.newJobBuilder() 
       .setService(MyJobService.class) 
       .setTag("my-job-tag") 
       .build(); 
     dispatcher.schedule(myJob); 
     // [END dispatch_job] 
    } 

    /** 
    * Handle time allotted to BroadcastReceivers. 
    */ 
    private void handleNow() { 
     Log.d(TAG, "Short lived task is done."); 
    } 

    /** 
    * Create and show a simple notification containing the received FCM message. 
    * 
    * @param messageBody FCM message body received. 
    */ 
    private void sendNotification(String messageBody) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.notification_bg) 
       .setContentTitle("FCM Message") 
       .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) 
       .setLights(Color.RED, 3000, 3000) 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
} 
+0

通知を送信するために使用するコードを追加できますか? –

+0

あなたが使用しているインテントは 'MainActivitiy.class'に属しています。あなたのコードの 'sendNotification()'の中でこの行を見てください: 'Intent intent = new Intent(this、MainActivity.class);'。それを 'Notification.class'に変更してください。 – ZeekHuge

+0

私は今firebaseを通して通知を送っています。 はい私はIntent intent = new Intent(this、Notification.class)に変更しました。まだmainActivityが表示されます –

答えて

3

おそらくこれに意図を変更する、ということである:

Intent intent = new Intent(this, Notification.class); 

のでにはのみAPIからMainActivity以外の活動を開くことはできませんあなたfirebaseコンソールからを明らかにする。なぜ

ための二つのこと。

コンソールから送られた通知はonMessageReceived発動しません()。

firebase cosole通知はpossibilyアクションをクリックし設定する必要はありません。を修正する

ウェイ:

APIからの通知を送信し、click_actionsを設定します。

例:

<?php 



#API access key from Google API's Console 



    define('API_ACCESS_KEY', 'YOUR_API_KEY'); 



    $topic = "/topics/todos"; 



$url = 'https://fcm.googleapis.com/fcm/send'; 

$fields = array (

     'to' => $topic, 

     'notification' => array (

       "body" => "nova casa adicionada", 

       "title" => "Nova casa", 

       "sound"=> "default", 

       "click_action"=> "Notification" 

     ), 

     'data' => array(

      "localcasa" => "Porto", 

      "precocasa"=> "1.600.000 €", 

      "imgurl"=> "http://brunoferreira.esy.es/imgsandroid/casa10.jpg", 

      "infocs"=> "Apartamento localizado em local premium da cidade do Porto, à Avenida Marechal Gomes da Costa, onde pode viver-se com toda a calma e descontração. No ponto mais elevado da Foz, com vista de mar e uma envolvente de luxo, rodeado por moradias, com exteriores amplos e vistas deslumbrantes. É constituída por 4 quartos, 5 casas de banho e uma garagem em que tem a capacidade para 2 carros.", 

      "csid"=> "10" 

     ) 

); 

$fields = json_encode ($fields); 

$headers = array (

     'Authorization: key=' . API_ACCESS_KEY, 

     'Content-Type: application/json' 

); 



$ch = curl_init(); 

curl_setopt ($ch, CURLOPT_URL, $url); 

curl_setopt ($ch, CURLOPT_POST, true); 

curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers); 

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 

curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields); 



$result = curl_exec ($ch); 

curl_close ($ch); 



?> 

そしてアンドロイドマニフェストセットで、この内部通知actifityclick_作用を設定する:

<intent-filter> 
       <action android:name="Notification" /> 

       <category android:name="android.intent.category.DEFAULT" /> 

      </intent-filter> 
+0

は、私ができる私は私がGoogleのAPIサービスを使用する場合、API –

+0

を働いていない試してみましたオールインワンにアップロードするか、私は郵便配達員を使用することができます –

+0

任意の便利なのresouces @DreamDeveloperあなたの問題の説明と私の答えを更新し –

0

JSONにサーバから送信アプリ

{ 

    "notification": { 
    "title": "Title", 
    "text": "notification", 
    "icon": "ic_launcher", 
    "click_action": "NOTIFICATION_ACTIVITY" 
    } 
} 

アンドロイドMenifestでこれを置く:

<activity 
      android:name=".acitivy.MainActivity" 
      android:screenOrientation="portrait" 
      android:theme="@style/AppTheme" > 

     <intent-filter> 
      <action android:name="NOTIFICATION_ACTIVITY" /> 

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

</activity> 

そしてあなたのMyFirebaseMessagingServiceに。

private void sendNotification(RemoteMessage remoteMessage, String messageBody) { 
    Intent intent = new Intent(this, MainActivity.class); 

    **//Add this line** 
    Map<String, String> extra = remoteMessage.getData(); 
    for (Map.Entry<String, String> entry : extra.entrySet()) { 
     intent.putExtra(entry.getKey(), entry.getValue()); 
    } 

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); 

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
      .setDefaults(Notification.DEFAULT_ALL) 
      .setSmallIcon(Build.VERSION.SDK_INT > 20 ? R.drawable.notification_icon_white : R.mipmap.ic_launcher_normal) 
      //.setLargeIcon(Build.VERSION.SDK_INT > 20 ? BitmapFactory.decodeResource(getResources(), R.drawable.notification_icon_white) : BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_normal)) 
      .setContentTitle(getString(R.string.app_name)) 
      .setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat.DEFAULT_VIBRATE | NotificationCompat.DEFAULT_LIGHTS) 
      .setColor(ContextCompat.getColor(this, R.color.colorPrimary)) 
      .setPriority(Notification.PRIORITY_HIGH) 
      .setContentText(messageBody) 
      .setAutoCancel(true) 
      .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody)) 
      .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND) 
      .setSound(defaultSoundUri) 
      .setContentIntent(pendingIntent); 

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL; 
    notificationManager.notify(getID(), notificationBuilder.build()); 
} 
0

をごsendNotifcationメソッド内のコードを変更します。sendNotificationをメソッド内のクラスは、以下を追加します。ご覧のとおり、NotificationActivity.classの代わりにMainAcitivity.classと書いてあります。あなたが入力したものと推測します

/** 
    * Create and show a simple notification containing the received FCM message. 
    * 
    * @param messageBody FCM message body received. 
    */ 
    private void sendNotification(String messageBody) { 
     Intent intent = new Intent(this, NotificationActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.notification_bg) 
       .setContentTitle("FCM Message") 
       .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) 
       .setLights(Color.RED, 3000, 3000) 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
+0

私は試しました 意図インテント=新しいインテント(this、NotificationActivity.class); –

0

私が提供したコードにsendNotification()が見つかりませんでした。表示される通知がの代わりにsendNotification()ではないことは確かです。 this pageを参照してください。アプリケーションがバックグラウンドで、通知ペイロードに通知パーツが含まれている場合、通知がシステムトレイに配信されます。システムトレイには、クリックするとランチャアクティビティが開始され、通知のデータがランチャアクティビティにバンドル形式で渡されます。

問題を解決するには、データメッセージのみを送信し、onMessageReceived()の適切な場所にNotification.classを入力してsendNotification()に電話してください。

関連する問題