📜 ⬆️ ⬇️

Nuances of Firebase messaging for beginners

After the publication on Habré of Artyom Osipov’s article “ Push notifications to Android using Firebase Cloud Messaging for beginners, ” a number of questions arose that could be resolved.

It was possible to achieve sending Push notifications with vibration and with their own sound + a notification in the status bar has a large icon and next to it all text. And it does not matter whether the application is active or hanging in the background - when you click on a notification, the Main Activity is always updated and carries the parameters from the notification.

So, in layout activity_mail.xml, we add two TextViews: one for the notification header and one for the text.

In MainActivity between:
')
setContentView(R.layout.activity_main); 

and

 Button subscribeButton = (Button) findViewById(R.id.subscribeButton); 

delete all lines and insert:

  TextView titleText = (TextView)findViewById(R.id.textView); TextView bodyText = (TextView)findViewById(R.id.textView2); // [START handle_data_extras] if (getIntent().getExtras() != null) { Intent intent = getIntent(); String title = intent.getStringExtra("title"); String body = intent.getStringExtra("body"); titleText.setText(title); bodyText.setText(body); } 

In the file MyFirebaseMessagingService function

 onMessageReceived 

should have this code:

 public void onMessageReceived(RemoteMessage remoteMessage) { sendNotification (remoteMessage.getData().get("title"), remoteMessage.getData().get("body")); } 

and function

 sendNotification 

should accept a code like this:

 private void sendNotification(String messageTitle, String messageBody) { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("title", messageTitle); intent.putExtra("body", messageBody); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_krolik); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_stat_s1) .setLargeIcon(largeIcon) .setColor(Color.parseColor("#4B8A08")) .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody)) .setContentTitle(messageTitle) .setContentText(messageBody) .setAutoCancel(true) .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.circles0)) .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) .setLights(Color.MAGENTA, 500, 1000) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } 

Where

 R.drawable.ic_krolik 

this is my notification icon, and

 R.raw.circles0 

This is my .mp3 file for the soundtrack of an incoming notification placed in the raw directory.

I send notifications via CURL. At first for tests I tried to do it from the Raspberry Pi terminal, where the line looked like this:

 curl -s "https://gcm-http.googleapis.com/gcm/send" -H "Authorization: key=AIzaSyB4ZanJWaCay_fXxO5z0jI55T8UOwdGNNQ" -H "Content-Type: application/json" -d '{"to": "fJuOOiTAk4w:APA91bHLrg95cyxodZDULzXU604BXJZUJKBaV8LHCbWPvMUlBhr6tzeD7TfNUp1rOMMObYmnC87OyqwRFbROjZV_pGUtNEh1fGFPDf0ApgljyDrLYEmAneKycVX5jCf8Rm2lpC7MDCss","priority" : "high", "vibrate": 1, "notification": { "title": "Port", "body" : "great", "sound": "circles0.mp3", "color": "#379F00", "icon" : "ic_stat_s"}, "data": {"title" : "3.21.15", "body": 12345678}}' 

but when the application is in the background or closed, the notification came in a stripped-down text format without vibration, but with its own sound and icon. I had to send CURL from PHP. First, install CURL in Raspberry Pi:

 sudo apt-get install curl libcurl3 libcurl3-dev php5-curl 

Create a PHP file:

 <?php // API access key from Google API's Console define( 'API_ACCESS_KEY', 'AIzaSyB4ZanJWaCay_fXxO5z0jI55T8UOwdGNNQ' ); $registrationIds = array( 'fJuOOiTAk4w:APA91bHLrg95cyxodZDULzXU604BXJZUJKBaV8LHCbWPvMUlBhr6tzeD7TfNUp1rOMMObYmnC87OyqwRFbROjZV_pGUtNEh1fGFPDf0ApgljyDrLYEmAneKycVX5jCf8Rm2lpC7MDCss' ); // prep the bundle $msg = array ( 'message' => 'here is a message. message', 'title' => 'This is a title. title', 'body' => 'This is a subtitle. subtitle, subtitle. subtitle subtitle. subtitle, subtitle. subtitle subtitle. subtitle, subtitle. subtitle subtitle. subtitle', 'tickerText' => 'Ticker text here...Ticker text here...Ticker text here', 'vibrate' => 1, 'sound' => 1, 'largeIcon' => 'large_icon', 'smallIcon' => 'small_icon' ); $fields = array ( 'registration_ids' => $registrationIds, 'data' => $msg ); $headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch ); echo $result; ?> 

From the terminal we start sending a notification:

 php curl.php 

and it does not matter what state our application is in: in the background or it works - we receive a notification with our own sound, with our own icon and the notification text contains all. When you click on the notification (if the application is running), the main activity is updated and the title and body of the notification will be placed in two TextViews. If the application is in the background, then it starts with the above result.

If we want another activation to open when we click on the notification, then we do this:
create another activity called Main2Activity. In the manifesto before

 </application> 

add code:

 <activity android:name=".Main2Activity"> <intent-filter> <action android:name="OPEN_ACTIVITY_1" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> 

In CURL, add the value

 "click_action": "OPEN_ACTIVITY_1" 

Source: https://habr.com/ru/post/303514/


All Articles