Skip to content

Commit

Permalink
Merge pull request #30 from virresh/push_notifs
Browse files Browse the repository at this point in the history
Push notifications merged
  • Loading branch information
gupta-meghna64 authored Nov 5, 2019
2 parents 01e6b56 + 016c54c commit c462fee
Show file tree
Hide file tree
Showing 6 changed files with 221 additions and 8 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,6 @@ dependencies {
implementation 'com.neovisionaries:nv-websocket-client:2.9'
implementation 'org.webrtc:google-webrtc:1.0.28513'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
implementation 'com.google.firebase:firebase-messaging:20.0.0'

}
44 changes: 36 additions & 8 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,63 @@
package="com.mobilecomputing.sahayak">

<application
tools:replace="android:allowBackup"
android:allowBackup="false"
android:fullBackupContent="false"
android:icon="@drawable/app_logo"
android:label="@string/app_name"
android:roundIcon="@drawable/app_logo"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
tools:replace="android:allowBackup">

<!-- [START fcm_default_icon] -->
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/app_logo" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<!-- [END fcm_default_icon] -->
<!-- [START fcm_default_channel] -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
<!-- [END fcm_default_channel] -->

<activity android:name=".Activities.UserDashboard" />
<activity android:name=".Activities.ProposalInformationActivity"></activity>

<activity android:name=".Activities.ProposalInformationActivity" />
<activity android:name=".Activities.MenteeOptionsActivity" />
<activity android:name=".Activities.MentorOptionsActivity" />
<activity android:name=".Activities.MentorMeetings"/>
<activity android:name=".Activities.MenteeMeetings"/>
<activity android:name=".Activities.MentorMeetings" />
<activity android:name=".Activities.MenteeMeetings" />
<activity android:name=".Activities.SignInActivity" />
<activity android:name=".Activities.OnboardingActivity" />
<activity android:name=".Activities.SessionActivity"/>
<activity android:name=".Activities.SessionActivity" />
<activity android:name=".Activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".FireBaseFCMService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.CAMERA" />

</manifest>
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.mobilecomputing.sahayak.Activities;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
Expand All @@ -23,6 +26,16 @@ protected void onCreate(Bundle savedInstanceState) {
getSupportActionBar().hide();
setContentView(R.layout.activity_main);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
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_DEFAULT));
}

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.mobilecomputing.sahayak.Activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
Expand All @@ -21,6 +22,7 @@
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.mobilecomputing.sahayak.FireBaseFCMService;
import com.mobilecomputing.sahayak.R;

public class SignInActivity extends AppCompatActivity implements View.OnClickListener {
Expand Down Expand Up @@ -71,6 +73,8 @@ public void onComplete(@NonNull Task<AuthResult> task) {
// TODO: Possibly pass this user via this intent
Intent userDashboardIntent = new Intent(SignInActivity.this, UserDashboard.class);
startActivity(userDashboardIntent);
String tok = FireBaseFCMService.getToken(getApplicationContext());
FireBaseFCMService.sendRegistrationToServer(tok);
setResult(RESULT_OK);
finish();
} else {
Expand Down
164 changes: 164 additions & 0 deletions app/src/main/java/com/mobilecomputing/sahayak/FireBaseFCMService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package com.mobilecomputing.sahayak;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.mobilecomputing.sahayak.Activities.MainActivity;

public class FireBaseFCMService 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.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
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());

if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
// scheduleJob();
Log.d(TAG, "Needed to schedule long job !");
} else {
// Handle message within 10 seconds
handleNow();
}

}

// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}

// 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.
}
// [END receive_message]


// [START on_new_token]

/**
* 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.
*/
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", token).apply();

// 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(token);
}
// [END on_new_token]

public static String getToken(Context context) {
return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
}

/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}

/**
* 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.
*/
public static void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference("users");
mDatabase.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("token").setValue(token);
mDatabase.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("email").setValue(FirebaseAuth.getInstance().getCurrentUser().getEmail());
}

/**
* 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);

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.app_logo)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// Since android Oreo notification channel is needed.
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 /* ID of notification */, notificationBuilder.build());
}

}
3 changes: 3 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,7 @@
<string name="accept_permissions_dialog">GIVE PERMISSIONS!</string>
<string name="cancel_dialog">CANCEL</string>
<string name="no_internet_connection">NO INTERNET CONNECTION, PLEASE CHECK YOUR CONNECTION</string>
<string name="default_notification_channel_id">SahayakMainChannel</string>
<string name="default_notification_channel_name">Sahayak</string>
<string name="fcm_message">Sayahak Notification</string>
</resources>

0 comments on commit c462fee

Please sign in to comment.