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
Step 1
Create a new project in Android Studio from File >> Project and fill in all the necessary details.
Enter your application package name. The Nick Name and Debug certificate SHA-1 are optional.
You need to download a google-services.json file and just move the downloaded google-services file into the Android app.
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
- classpath 'com.google.gms:google-services:3.2.0'
Gradle for app
- dependencies {
-
- compile 'com.google.firebase:firebase-core:12.0.0'
- compile 'com.google.firebase:firebase-messaging:12.0.0'
- compile 'com.firebase:firebase-jobdispatcher:0.8.5'
-
- }
- apply plugin: 'com.google.gms.google-services'
Step 4
Next, go to app >> manifest >> AndroidManifest.xml. Select the Manifest file to follow the code.
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="io.github.selvaraju_saravanan.notify">
-
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
- 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>
- <service android:name=".MyJobService"
- android:exported="false">
- <intent-filter>
- <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
- </intent-filter>
- </service>
- </application>
-
- </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
- <resources>
- <!-- Default screen margins, per the Android Design guidelines. -->
- <dimen name="activity_horizontal_margin">16dp</dimen>
- <dimen name="activity_vertical_margin">16dp</dimen>
-
- <dimen name="standard_field_width">200dp</dimen>
- </resources>
String.xml code
- <resources>
- <string name="app_name">notification</string>
- <string name="quickstart_message">Click the SUBSCRIBE TO NEWS button below to subscribe to the
- news topic. Messages sent to the news topic will be received. The LOG TOKEN button logs the
- InstanceID token to logcat.</string>
- <string name="subscribe_to_news">Subscribe To News</string>
- <string name="log_token">Log Token</string>
- <string name="msg_subscribed">Subscribed to news topic</string>
- <string name="msg_token_fmt" translatable="false">InstanceID Token: %s</string>
- <string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
- <string name="default_notification_channel_name" translatable="true">News</string>
- </resources>
Activity_Main.xml Code
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="io.github.selvaraju_saravanan.notify.MainActivity">
-
- <Button
- android:id="@+id/subscribeButton"
- android:layout_width="@dimen/standard_field_width"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:layout_marginTop="20dp"
- android:text="@string/subscribe_to_news" />
-
- <Button
- android:id="@+id/logTokenButton"
- android:layout_width="@dimen/standard_field_width"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:text="@string/log_token" />
-
- </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
- package io.github.selvaraju_saravanan.notify;
-
- import android.app.NotificationChannel;
- import android.app.NotificationManager;
- import android.content.Context;
- import android.os.Build;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
- import com.google.firebase.iid.FirebaseInstanceId;
- import com.google.firebase.messaging.FirebaseMessaging;
-
- 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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
-
- String channelId = getString(R.string.default_notification_channel_id);
- String channelName = getString(R.string.default_notification_channel_name);
- NotificationManager notificationManager =
- getSystemService(NotificationManager.class);
- notificationManager.createNotificationChannel(new NotificationChannel(channelId,
- channelName, NotificationManager.IMPORTANCE_LOW));
- }
-
- if (getIntent().getExtras() != null) {
- for (String key : getIntent().getExtras().keySet()) {
- Object value = getIntent().getExtras().get(key);
- Log.d(TAG, "Key: " + key + " Value: " + value);
- }
- }
-
-
- Button subscribeButton = findViewById(R.id.subscribeButton);
- subscribeButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
-
- FirebaseMessaging.getInstance().subscribeToTopic("news");
-
-
-
- String msg = getString(R.string.msg_subscribed);
- Log.d(TAG, msg);
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
- }
- });
-
- Button logTokenButton = findViewById(R.id.logTokenButton);
- logTokenButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
-
- String token = FirebaseInstanceId.getInstance().getToken();
-
-
- String msg = getString(R.string.msg_token_fmt, token);
- Log.d(TAG, msg);
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- }
MyFirebaseMessageService.java Code
- package io.github.selvaraju_saravanan.notify;
-
- import android.app.NotificationChannel;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Context;
- import android.content.Intent;
- import android.media.RingtoneManager;
- import android.net.Uri;
- import android.os.Build;
- import android.support.v4.app.NotificationCompat;
- import android.util.Log;
- import com.firebase.jobdispatcher.Constraint;
- 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";
-
-
- @Override
- public void onMessageReceived(RemoteMessage remoteMessage) {
-
- Log.d(TAG, "From: " + remoteMessage.getFrom());
-
-
- if (remoteMessage.getData().size() > 0) {
- Log.d(TAG, "Message data payload: " + remoteMessage.getData());
-
- if ( true) {
-
- scheduleJob();
- } else {
-
- handleNow();
- }}
-
- if (remoteMessage.getNotification() != null) {
- Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
- }
-
-
- }
-
- private void scheduleJob() {
-
- FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
- Job myJob = dispatcher.newJobBuilder()
- .setService(MyJobService.class)
- .setTag("my-job-tag")
- .build();
- dispatcher.schedule(myJob);
-
- }
- private void handleNow() {
- Log.d(TAG, "Short lived task is done.");
- }
- 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 , intent,
- PendingIntent.FLAG_ONE_SHOT);
-
- String channelId = getString(R.string.default_notification_channel_id);
- Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
- NotificationCompat.Builder notificationBuilder =
- new NotificationCompat.Builder(this, channelId)
- .setSmallIcon(R.drawable.ic_launcher_background)
- .setContentTitle("FCM Message")
- .setContentText(messageBody)
- .setAutoCancel(true)
- .setSound(defaultSoundUri)
- .setContentIntent(pendingIntent);
-
- NotificationManager notificationManager =
- (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- NotificationChannel channel = new NotificationChannel(channelId,
- "Channel human readable title",
- NotificationManager.IMPORTANCE_DEFAULT);
- notificationManager.createNotificationChannel(channel);
- }
-
- notificationManager.notify(0 , notificationBuilder.build());
- }
- }
MyFirebaseInstanceIDService.java Code
- package io.github.selvaraju_saravanan.notify;
-
- import android.util.Log;
- import com.google.firebase.iid.FirebaseInstanceId;
- import com.google.firebase.iid.FirebaseInstanceIdService;
-
- public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
-
- private static final String TAG = "MyFirebaseIIDService";
- @Override
- public void onTokenRefresh() {
-
- String refreshedToken = FirebaseInstanceId.getInstance().getToken();
- Log.d(TAG, "Refreshed token: " + refreshedToken);
- sendRegistrationToServer(refreshedToken);
- }
- private void sendRegistrationToServer(String token) {}
- }
MyJobService.java Code
- package io.github.selvaraju_saravanan.notify;
-
- import android.util.Log;
- import com.firebase.jobdispatcher.JobParameters;
- import com.firebase.jobdispatcher.JobService;
-
- public class MyJobService extends JobService {
-
- private static final String TAG = "MyJobService";
-
- @Override
- public boolean onStartJob(JobParameters jobParameters) {
- Log.d(TAG, "Performing long running task in scheduled job");
- return false;
- }
-
- @Override
- public boolean onStopJob(JobParameters jobParameters) {
- return false;
- }
-
- }
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.
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.
Your Analytics data will appear here soon.
Geographical View
Finally, Firebase has collected all information on your device including your device name, version, etc.
Your device is located here (Mobile Name and Location ).
We have successfully created the Location View app.