StreamView Your Location Using Android Studio And InstanceID Token

Introduction

 
This article demonstrates how to add StreamView Location on an Android application using Android Studio and InstanceID token. Also, you will see how to send the new Firebase InstanceID token to your cloud.
 

StreamView

 
A Windows analytics event in your app, StreamView gives you a live view of the events as they are collected by the report. StreamView collects the information for the last 30 minutes. There is no setup needed to use StreamView.
 

Geographical View

 
Android
 
Step 1
 
Create a new project in Android Studio from File >> Project and fill in all the necessary details.
 
Android 
 
Step 2
 
Create a new project in Firebase console.
 
Android
 
Enter your application package name. The Nick Name and Debug certificate SHA-1 are optional. 
 
Android
 
You need to download a google-services.json file and just move the downloaded google-services file into the Android app.
 
Android 
 
Android 
 
Step 3
 
Next, go to Gradle Scripts >> build.gradle (Module: app).Select build.gradle. 
 
The app Gradle compiles the code, and then the build types will appear.
 
Just replace that with the following code and add the Firebase Core and Firebase Message Gradle to your project, or you can also use Gradle.
 
Dependencies Class
  1. classpath 'com.google.gms:google-services:3.2.0'  
Gradle for app
  1. dependencies {    
  2.   
  3.     compile 'com.google.firebase:firebase-core:12.0.0'    
  4.     compile 'com.google.firebase:firebase-messaging:12.0.0'    
  5.     compile 'com.firebase:firebase-jobdispatcher:0.8.5'  
  6.   
  7. }    
  8. apply plugin: 'com.google.gms.google-services'  
Step 4
 
Next, go to app >> manifest >> AndroidManifest.xml. Select the Manifest file to follow the code.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="io.github.selvaraju_saravanan.notify">  
  4.   
  5.     <application  
  6.         android:allowBackup="true"  
  7.         android:icon="@mipmap/ic_launcher"  
  8.         android:label="@string/app_name"  
  9.         android:roundIcon="@mipmap/ic_launcher_round"  
  10.         android:supportsRtl="true"  
  11.         android:theme="@style/AppTheme">  
  12.         <activity android:name=".MainActivity">  
  13.             <intent-filter>  
  14.                 <action android:name="android.intent.action.MAIN" />  
  15.   
  16.                 <category android:name="android.intent.category.LAUNCHER" />  
  17.             </intent-filter>  
  18.         </activity>  
  19.         <service  
  20.             android:name=".MyFirebaseMessagingService">  
  21.             <intent-filter>  
  22.                 <action android:name="com.google.firebase.MESSAGING_EVENT"/>  
  23.             </intent-filter>  
  24.         </service>  
  25.         <service  
  26.             android:name=".MyFirebaseInstanceIDService">  
  27.             <intent-filter>  
  28.                 <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>  
  29.             </intent-filter>  
  30.         </service>  
  31.         <service android:name=".MyJobService"  
  32.             android:exported="false">  
  33.             <intent-filter>  
  34.                 <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>  
  35.             </intent-filter>  
  36.         </service>  
  37.     </application>  
  38.   
  39. </manifest>  
Next, go to app >> res >> values >> string and dimens.xml. Select these two files to follow the code as given below.
 
Dimens.xml code
  1. <resources>  
  2.     <!-- Default screen margins, per the Android Design guidelines. -->  
  3.     <dimen name="activity_horizontal_margin">16dp</dimen>  
  4.     <dimen name="activity_vertical_margin">16dp</dimen>  
  5.   
  6.     <dimen name="standard_field_width">200dp</dimen>  
  7. </resources>  
String.xml code
  1. <resources>  
  2.     <string name="app_name">notification</string>  
  3.         <string name="quickstart_message">Click the SUBSCRIBE TO NEWS button below to subscribe to the  
  4.         news topic. Messages sent to the news topic will be received. The LOG TOKEN button logs the  
  5.         InstanceID token to logcat.</string>  
  6.         <string name="subscribe_to_news">Subscribe To News</string>  
  7.         <string name="log_token">Log Token</string>  
  8.         <string name="msg_subscribed">Subscribed to news topic</string>  
  9.         <string name="msg_token_fmt" translatable="false">InstanceID Token: %s</string>  
  10.         <string name="default_notification_channel_id" translatable="false">fcm_default_channel</string> 
  11.         <string name="default_notification_channel_name" translatable="true">News</string>  
  12.     </resources>  
Activity_Main.xml Code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="io.github.selvaraju_saravanan.notify.MainActivity">  
  8.   
  9.     <Button  
  10.         android:id="@+id/subscribeButton"  
  11.         android:layout_width="@dimen/standard_field_width"  
  12.         android:layout_height="wrap_content"  
  13.         android:layout_gravity="center_horizontal"  
  14.         android:layout_marginTop="20dp"  
  15.         android:text="@string/subscribe_to_news" />  
  16.   
  17.     <Button  
  18.         android:id="@+id/logTokenButton"  
  19.         android:layout_width="@dimen/standard_field_width"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_gravity="center_horizontal"  
  22.         android:text="@string/log_token" />  
  23.   
  24. </LinearLayout>  
Step 5
 
Next, go to app >> Java >> package name >> New Java Class. Select the Java Class name as MyFirebaseMessageService.java,
 
MyFirebaseInstanceIDService, MyJobService.java and put in the following code.
 
MainActivity.java code
  1. package io.github.selvaraju_saravanan.notify;  
  2.   
  3. import android.app.NotificationChannel;  
  4. import android.app.NotificationManager;  
  5. import android.content.Context;  
  6. import android.os.Build;  
  7. import android.os.Bundle;  
  8. import android.support.v7.app.AppCompatActivity;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.widget.Button;  
  12. import android.widget.Toast;
  13. import com.google.firebase.iid.FirebaseInstanceId;  
  14. import com.google.firebase.messaging.FirebaseMessaging;  
  15.   
  16. public class MainActivity extends AppCompatActivity {  
  17.   
  18.     private static final String TAG = "MainActivity";  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.   
  25.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  
  26.              
  27.             String channelId  = getString(R.string.default_notification_channel_id);  
  28.             String channelName = getString(R.string.default_notification_channel_name);  
  29.             NotificationManager notificationManager =  
  30.                     getSystemService(NotificationManager.class);  
  31.             notificationManager.createNotificationChannel(new NotificationChannel(channelId,  
  32.                     channelName, NotificationManager.IMPORTANCE_LOW));  
  33.         }  
  34.   
  35.         if (getIntent().getExtras() != null) {  
  36.             for (String key : getIntent().getExtras().keySet()) {  
  37.                 Object value = getIntent().getExtras().get(key);  
  38.                 Log.d(TAG, "Key: " + key + " Value: " + value);  
  39.             }  
  40.         }  
  41.         // [END handle_data_extras]  
  42.   
  43.         Button subscribeButton = findViewById(R.id.subscribeButton);  
  44.         subscribeButton.setOnClickListener(new View.OnClickListener() {  
  45.             @Override  
  46.             public void onClick(View v) {  
  47.                 // [START subscribe_topics]  
  48.                 FirebaseMessaging.getInstance().subscribeToTopic("news");  
  49.                 // [END subscribe_topics]  
  50.   
  51.                 // Log and toast  
  52.                 String msg = getString(R.string.msg_subscribed);  
  53.                 Log.d(TAG, msg);  
  54.                 Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();  
  55.             }  
  56.         });  
  57.   
  58.         Button logTokenButton = findViewById(R.id.logTokenButton);  
  59.         logTokenButton.setOnClickListener(new View.OnClickListener() {  
  60.             @Override  
  61.             public void onClick(View v) {  
  62.                 // Get token  
  63.                 String token = FirebaseInstanceId.getInstance().getToken();  
  64.   
  65.                 // Log and toast  
  66.                 String msg = getString(R.string.msg_token_fmt, token);  
  67.                 Log.d(TAG, msg);  
  68.                 Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();  
  69.             }  
  70.         });  
  71.     }  
  72.   
  73. }  
MyFirebaseMessageService.java Code
  1. package io.github.selvaraju_saravanan.notify;  
  2.   
  3. import android.app.NotificationChannel;  
  4. import android.app.NotificationManager;  
  5. import android.app.PendingIntent;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.media.RingtoneManager;  
  9. import android.net.Uri;  
  10. import android.os.Build;  
  11. import android.support.v4.app.NotificationCompat;  
  12. import android.util.Log; 
  13. import com.firebase.jobdispatcher.Constraint;  
  14. import com.firebase.jobdispatcher.FirebaseJobDispatcher;  
  15. import com.firebase.jobdispatcher.GooglePlayDriver;  
  16. import com.firebase.jobdispatcher.Job;  
  17. import com.google.firebase.messaging.FirebaseMessagingService;  
  18. import com.google.firebase.messaging.RemoteMessage;  
  19.   
  20. public class MyFirebaseMessagingService extends FirebaseMessagingService {  
  21.   
  22.     private static final String TAG = "MyFirebaseMsgService";  
  23.   
  24.  
  25.     @Override  
  26.     public void onMessageReceived(RemoteMessage remoteMessage) {  
  27.        
  28.         Log.d(TAG, "From: " + remoteMessage.getFrom());  
  29.   
  30.         // Check if message contains a data payload.  
  31.         if (remoteMessage.getData().size() > 0) {  
  32.             Log.d(TAG, "Message data payload: " + remoteMessage.getData());  
  33.   
  34.             if ( true) {  
  35.                   
  36.                 scheduleJob();  
  37.             } else {  
  38.                   
  39.                 handleNow();  
  40.             }}
  41.         // Check if message contains a notification payload.  
  42.         if (remoteMessage.getNotification() != null) {  
  43.             Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());  
  44.         }  
  45.   
  46.         
  47.     }  
  48.    
  49.     private void scheduleJob() {  
  50.  
  51.         FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));  
  52.         Job myJob = dispatcher.newJobBuilder()  
  53.                 .setService(MyJobService.class)  
  54.                 .setTag("my-job-tag")  
  55.                 .build();  
  56.         dispatcher.schedule(myJob);  
  57.         // [END dispatch_job]  
  58.     }
  59.     private void handleNow() {  
  60.         Log.d(TAG, "Short lived task is done.");  
  61.     } 
  62.     private void sendNotification(String messageBody) {  
  63.         Intent intent = new Intent(this, MainActivity.class);  
  64.         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  65.         PendingIntent pendingIntent = PendingIntent.getActivity(this0 /* Request code */, intent,  
  66.                 PendingIntent.FLAG_ONE_SHOT);  
  67.   
  68.         String channelId = getString(R.string.default_notification_channel_id);  
  69.         Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);  
  70.         NotificationCompat.Builder notificationBuilder =  
  71.                 new NotificationCompat.Builder(this, channelId)  
  72.                         .setSmallIcon(R.drawable.ic_launcher_background)  
  73.                         .setContentTitle("FCM Message")  
  74.                         .setContentText(messageBody)  
  75.                         .setAutoCancel(true)  
  76.                         .setSound(defaultSoundUri)  
  77.                         .setContentIntent(pendingIntent);  
  78.   
  79.         NotificationManager notificationManager =  
  80.                 (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
  81.   
  82.         
  83.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  
  84.             NotificationChannel channel = new NotificationChannel(channelId,  
  85.                     "Channel human readable title",  
  86.                     NotificationManager.IMPORTANCE_DEFAULT);  
  87.             notificationManager.createNotificationChannel(channel);  
  88.         }  
  89.   
  90.         notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());  
  91.     }  
  92. }  
MyFirebaseInstanceIDService.java Code
  1. package io.github.selvaraju_saravanan.notify;  
  2.   
  3. import android.util.Log;  
  4. import com.google.firebase.iid.FirebaseInstanceId;  
  5. import com.google.firebase.iid.FirebaseInstanceIdService;  
  6.   
  7. public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {  
  8.   
  9.     private static final String TAG = "MyFirebaseIIDService";  
  10.     @Override  
  11.     public void onTokenRefresh() {  
  12.          
  13.         String refreshedToken = FirebaseInstanceId.getInstance().getToken();  
  14.         Log.d(TAG, "Refreshed token: " + refreshedToken);  
  15.         sendRegistrationToServer(refreshedToken);  
  16.     }  
  17.     private void sendRegistrationToServer(String token) {}  
  18. }  
MyJobService.java Code
  1. package io.github.selvaraju_saravanan.notify;  
  2.   
  3. import android.util.Log;
  4. import com.firebase.jobdispatcher.JobParameters;  
  5. import com.firebase.jobdispatcher.JobService;  
  6.   
  7. public class MyJobService extends JobService {  
  8.   
  9.     private static final String TAG = "MyJobService";  
  10.   
  11.     @Override  
  12.     public boolean onStartJob(JobParameters jobParameters) {  
  13.         Log.d(TAG, "Performing long running task in scheduled job");  
  14.         return false;  
  15.     }  
  16.   
  17.     @Override  
  18.     public boolean onStopJob(JobParameters jobParameters) {  
  19.         return false;  
  20.     }  
  21.   
  22. }  
Step 6
 
After that, again, go back to Console Firebase > Click OverView. This shows daily active users and monthly active users in the view but there is no active count.
 
Android 
 
Android
 
Step 7
 
Next, go to Android Studio and deploy the application. Select Emulator or your Android Device with USB debugging enabled. Give it a few seconds to make installations and set permissions.
 
Output
 
When you click the "Subscribe" button, it is getting an InstanceID token. If you want to click Log Token, your StreamView user gets active on the Firebase cloud side.
 
Android 
 
Your Analytics data will appear here soon.
 
Android 
 

Geographical View

 
Finally, Firebase has collected all information on your device including your device name, version, etc.
 
Android 
 
Your device is located here (Mobile Name and Location ).
 
Android 
 
We have successfully created the Location View app.
 
Refer to my previous article Push Notification Using the Android Studio And Google Firebase to get started with the basics of Firebase.


Similar Articles