Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- }
- }
- 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) {
- // [START_EXCLUDE]
- // 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
- // [END_EXCLUDE]
- // TODO(developer): Handle FCM messages here.
- Log.d(TAG, "From: " + remoteMessage.getFrom());
- //Toast.makeText(getApplicationContext(),"FROM "+remoteMessage.getFrom(),Toast.LENGTH_LONG).show();
- // Check if message contains a data payload.
- if (remoteMessage.getData().size() > 0) {
- Log.d(TAG, "Message data payload: " + remoteMessage.getData());
- //Toast.makeText(getApplicationContext(),"MESSAGE: "+remoteMessage.getData(),Toast.LENGTH_LONG).show();
- }
- // Check if message contains a notification payload.
- if (remoteMessage.getNotification() != null) {
- //MainActivity.TestMethod();
- Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
- //Toast.makeText(getApplicationContext(),"MESSAGE: "+remoteMessage.getData(),Toast.LENGTH_LONG).show();
- }
- // Also if you intend on generating your own notifications as a result of a received FCM
- // message, here is where that should be initiated. See sendNotification method below.
- sendNotification(remoteMessage.getNotification().getBody());
- }
- // [END receive_message]
- /**
- * 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.ic_stat_ic_notification)
- .setContentTitle("FCM Message")
- .setContentText(messageBody)
- .setAutoCancel(true)
- .setSound(defaultSoundUri)
- .setContentIntent(pendingIntent);
- NotificationManager notificationManager =
- (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
- }
- }
- public class MainActivity extends AppCompatActivity {
- private static final String TAG = "MainActivity";
- @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 sample 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.
- // [START handle_data_extras]
- if (getIntent().getExtras() != null) {
- for (String key : getIntent().getExtras().keySet()) {
- String value = getIntent().getExtras().getString(key);
- Log.d(TAG, "Key: " + key + " Value: " + value);
- }
- }
- // [END handle_data_extras]
- Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
- subscribeButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // [START subscribe_topics]
- FirebaseMessaging.getInstance().subscribeToTopic("news");
- // [END subscribe_topics]
- // Log and toast
- String msg = getString(R.string.msg_subscribed);
- Log.d(TAG, msg);
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
- }
- });
- Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
- logTokenButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // Get token
- String token = FirebaseInstanceId.getInstance().getToken();
- // Log and toast
- String msg = getString(R.string.msg_token_fmt, token);
- Log.d(TAG, msg);
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
- // Top-level build file where you can add configuration options commonto `all sub-projects/modules.`
- buildscript {
- repositories {
- jcenter()
- mavenLocal()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:2.1.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()
- mavenLocal()
- }
- }
- apply plugin: 'com.android.application'
- android {
- compileSdkVersion 24
- buildToolsVersion "24.0.0"
- defaultConfig {
- applicationId "com.google.firebase.quickstart.fcm"
- minSdkVersion 15
- targetSdkVersion 24
- versionCode 1
- versionName "1.0"
- testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- packagingOptions {
- exclude 'LICENSE.txt'
- }
- }
- dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- // Testing dependencies
- androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
- androidTestCompile 'com.android.support.test:runner:0.2'
- androidTestCompile 'com.android.support:support-annotations:24.2.0'
- compile 'com.android.support:appcompat-v7:24.2.0'
- compile 'com.google.firebase:firebase-messaging:9.4.0'
- compile 'com.google.firebase:firebase-core:9.4.0'
- compile 'com.google.android.gms:play-services-gcm:9.4.0'
- compile 'com.android.support:design:24.2.0'
- }
- apply plugin: 'com.google.gms.google-services'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement