Step 1:---------------------------MainActivity.java
package com.edupointbd.amirul.notificationdemourl; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // If a notification message is tapped, any data accompanying the notification // message is available in the intent extras. In this project the launcher // intent is fired when the notification is tapped, so any accompanying data would // be handled here. If you want a different intent fired, set the click_action // field of the notification message to the desired intent. The launcher intent // is used when no click_action is specified. // // Handle possible data accompanying notification message. if (getIntent().getExtras() != null) { if (getIntent().getStringExtra("LINK")!=null) { Intent i=new Intent(this,AnotherActivity.class); i.putExtra("link",getIntent().getStringExtra("LINK")); MainActivity.this.startActivity(i); finish(); }} subscribeToPushService(); } private void subscribeToPushService() { FirebaseMessaging.getInstance().subscribeToTopic("news"); Log.d("AndroidBash", "Subscribed"); Toast.makeText(MainActivity.this, "Subscribed", Toast.LENGTH_SHORT).show(); String token = FirebaseInstanceId.getInstance().getToken(); try { // Log and toast Log.d("AndroidBash", token); Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show(); }catch (NullPointerException e){ e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.edupointbd.amirul.notificationdemourl.MainActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_gravity="center_horizontal" android:src="@drawable/ic_stat_ict_hub" /> <TextView android:id="@+id/informationTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_horizontal" android:text="@string/app_name" /> </RelativeLayout>step 2:AnotherActivity .javapackage com.edupointbd.amirul.notificationdemourl; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; public class AnotherActivity extends AppCompatActivity { TextView tvT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_another); WebView webView = (WebView) findViewById(R.id.web); Intent i = getIntent(); String url = i.getStringExtra("link"); if (!url.startsWith("http://") && !url.startsWith("https://")) { url = "http://" + url; webView.loadUrl(url); Intent ii = new Intent(Intent.ACTION_VIEW); ii.setData(Uri.parse(url)); startActivity(ii); } Toast.makeText(getApplicationContext(),url,Toast.LENGTH_LONG).show(); } }activity_anothe.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_another" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.edupointbd.amirul.notificationdemourl.AnotherActivity"> <WebView android:id="@+id/web" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerVertical="true" /> </RelativeLayout>step 3:package com.edupointbd.amirul.notificationdemourl; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Amirul on 24-Sep-17. */ public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ // [START refresh_token] @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. sendRegistrationToServer(refreshedToken); } // [END refresh_token] /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // TODO: Implement this method to send token to your app server. } }step 4:package com.edupointbd.amirul.notificationdemourl; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Amirul on 24-Sep-17. */ public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebaseMessageService"; Bitmap bitmap; /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { // There are two types of messages data messages and notification messages. Data messages are handled // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated notification is displayed. // When the user taps on the notification they are returned to the app. Messages containing both notification // and data payloads are treated as notification messages. The Firebase console always sends notification // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options // 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()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } //The message which i send will have keys named [message, image, AnotherActivity] and corresponding values. //You can change as per the requirement. //message will contain the Push Message String message = remoteMessage.getData().get("message"); //imageUri will contain URL of the image to be displayed with Notification String imageUri = remoteMessage.getData().get("image"); //If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened. //If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened. String TrueOrFlase = remoteMessage.getData().get("AnotherActivity"); //To get a Bitmap image from the URL received bitmap = getBitmapfromUrl(imageUri); sendNotification(message, bitmap, TrueOrFlase); } /** * Create and show a simple notification containing the received FCM message. */ private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("LINK", messageBody); 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) .setLargeIcon(image)/*Notification icon image*/ .setSmallIcon(R.drawable.ic_stat_ict_hub) .setContentTitle(messageBody) .setStyle(new NotificationCompat.BigPictureStyle() .bigPicture(image))/*Notification with Image*/ .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } /* *To get a Bitmap image from the URL received * */ public Bitmap getBitmapfromUrl(String imageUrl) { try { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(input); return bitmap; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }step 5:<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.edupointbd.amirul.notificationdemourl"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name=".MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> <activity android:name=".AnotherActivity"></activity> </application> </manifest>step 6:// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.3' classpath 'com.google.gms:google-services:3.0.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }step 7:apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.edupointbd.amirul.notificationdemourl" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.google.firebase:firebase-core:9.4.0' compile 'com.google.firebase:firebase-messaging:9.4.0' compile 'com.google.android.gms:play-services-auth:9.4.0' testCompile 'junit:junit:4.12'} apply plugin: 'com.google.gms.google-services'step 8:to fixed devicehttps://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIza************adrTY { "data": { "image": "https://ibin.co/2t1lLdpfS06F.png", "message": "Firebase Push Message Using API" "AnotherActivity": "True" }, "to" : "f25gYF3***********************HLI" }all device same message to send{ "condition": "'news' in topics || 'cats' in topics", "data": { "image": "https://ibin.co/2t1lLdpfS06F.png", "message": "www.edupointbd.com", "AnotherActivity": "True", } }