For some reason my Firebase notifications are not showing in the foreground. They work fine in the background however, and I followed what Anroid Studio told me to add as well as this tutorial example on github
Judging by the Run window, it is receiving the notification but not sending in foreground
Here is my service code for sending the notification
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.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import static android.support.constraint.Constraints.TAG;
public class FirebaseNotificationsRecieverService extends FirebaseMessagingService {
private static final String TAG = FirebaseNotificationsRecieverService.class.getName();
public FirebaseNotificationsRecieverService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
System.out.println("RECIEVED");
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: (there was a link here)
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 Firebase Job Dispatcher.
//scheduleJob();
} 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());
}
sendNotification(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.
}
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 /* 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.wlmaclogo)
.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());
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starenkysoftware.macapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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"
android:usesCleartextTraffic="true">
<service
android:name=".FirebaseNotificationsRecieverService"
android:enabled="true"
android:exported="true"></service>
<service android:name="com.google.firebase.messaging.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Replace the manifest as below:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starenkysoftware.macapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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"
android:usesCleartextTraffic="true">
<service android:name=".FirebaseNotificationsRecieverService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The intent filter com.google.firebase.MESSAGING_EVENT should be placed in your service, which you are using to get the notifications.
Remember to remove the existing messaging service from the AndroidManifest.xml. If you leave the FireBaseMessagingService in the Manifest. your newly defined service doesn't get picked up.
E.g. remove the following:
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and add the following:
<service
android:name=".MyFirebaseNotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Related
I've created a custom deep link dispatcher in Java within a react native project.
The issue I'm having is that I can't get MainActivity to start from my dispatcher, and I can't quite figure out why.
I have AndroidManifest set up so that the deep link is captured in LinkDispatcherActivity effectively, but the startActivity(dispatchedIntent) never reaches MainActivity, which is where I assume it needs to go. Ordinarily in AndroidManifest.xml, deep links would be sent to MainActivity).
It does open the app, but I assume it's because LinkDispatcherActivity is part of the app? Not sure, if I say something dumb it's because this is only my 3rd day in a row writing Java 😰
Below is my code.
package com.example.app;
//Inspired by https://github.com/justeat/Android.Samples.Deeplinks, Licensed under Apache 2.0
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import net.openid.appauth.RedirectUriReceiverActivity;
public class LinkDispatcherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
dispatchIntent(getIntent());
} catch (IllegalArgumentException iae) {
// Malformed URL
if (BuildConfig.DEBUG) {
Log.e("Deep links", "Invalid URI", iae);
}
} finally {
// Always finish the activity so that it doesn't stay in our history
finish();
}
}
public void dispatchIntent(Intent intent) {
final Uri uri = intent.getData();
final String host = uri.getHost().toLowerCase();
if (uri == null) throw new IllegalArgumentException("Uri cannot be null");
// Default intent
Intent dispatchedIntent = new Intent(LinkDispatcherActivity.this, MainActivity.class);
dispatchedIntent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Log.d(dispatchedIntent.getDataString(), "dispatchIntent: intent string");
// Auth intent only, this is why I need the dispatcher
if ("login".equals(host)) {
dispatchedIntent = new Intent(this, RedirectUriReceiverActivity.class);
dispatchedIntent.putExtra("requestCode", 0);
Log.d("Login", "mapAppLink: ");
startActivityForResult(dispatchedIntent, 0);
return;
}
Log.d("Default", "mapAppLink: ");
startActivity(dispatchedIntent);
}
}
This is what my AndroidManifest.xml looks like:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
package="com.example.app">
<!-- < Only if you're using GCM or localNotificationSchedule() > -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="${applicationId}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<!-- < Only if you're using GCM or localNotificationSchedule() > -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".MainApplication"
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:theme="#style/AppTheme"
android:requestLegacyExternalStorage="true">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="<redacted>" />
<!-- < Notification Services > -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
tools:replace="android:resource"
android:resource="#color/colorAccent" />
<!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="true"/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
tools:replace="android:value"
android:value="rn-push-notification-channel-id" />
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name" android:value="Default Channel"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description" android:value="Default channel for push notifications"/>
<meta-data
android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="#color/colorAccent" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<!-- START: Add this-->
<service
android:name=".MainNotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<receiver
android:name="com.intercom.reactnative.RNIntercomPushBroadcastReceiver"
tools:replace="android:exported"
android:exported="true"/>
<activity
android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
android:launchMode="singleTask"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</activity>
<activity android:name=".LinkDispatcherActivity"
tools:node="replace">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="example"
android:host="login" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
Edit: for the intent, I've tried:
new Intent(getApplicationContext(), MainActivity.class)
new Intent(reactContext, MainActivity.class) (extending ReactActivity instead of Activity)
new Intent(this, MainActivity.class)
new Intent("MainActivity")
Try adding RedirectUriReceiverActivity to the manifest - I couldn't see it in there.
<activity android:name="com.facebook.react.devsupport.RedirectUriReceiverActivity" />
This is what I ended up with for the LinkDispatcherActivity. To summarize, what I did was dispatch the intents that the deep activities were eventually supposed to invoke directly, instead of trying to forward the intent. In other words, if you're trying to pass an intent from one activity to another, maybe don't and consider dispatching the activity/function/intent that you want to run afterwards. I still think forwarding the intent should have worked, but this is what ended up working.
In order to accomplish the above, I:
Called a function within the AppAuth package that generates an intent, and dispatch it
Used ReactContext to emit the url listener event that React Native uses to respond to deep links.
Below is the code:
//Inspired by https://github.com/justeat/Android.Samples.Deeplinks, Licensed under Apache 2.0
package com.example.app;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import net.openid.appauth.AuthorizationManagementActivity;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class LinkDispatcherActivity extends ReactActivity {
#Override
protected void onResume() {
super.onResume();
try {
dispatchIntent(getIntent());
} catch (IllegalArgumentException iae) {
// Malformed URL
if (BuildConfig.DEBUG) {
Log.e("Deep links", "Invalid URI", iae);
}
} finally {
// Always finish the activity so that it doesn't stay in our history
finish();
}
}
public void dispatchIntent(Intent intent) {
final Uri uri = intent.getData();
final String host = uri.getHost().toLowerCase();
if (uri == null) throw new IllegalArgumentException("Uri cannot be null");
// Default intent, e.g. settings, fitbit
// wait for react context
ReactInstanceManager reactInstanceManager = getReactInstanceManager();
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
Intent dispatchedIntent = new Intent(getApplicationContext(), MainActivity.class);
dispatchedIntent.setData(uri);
dispatchedIntent.putExtra("url", uri.toString());
dispatchedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Auth intent only
if ("login".equals(host)) {
Intent authIntent = AuthorizationManagementActivity.createResponseHandlingIntent(getApplicationContext(), uri);
startActivity(authIntent);
return;
}
// Below from https://stackoverflow.com/questions/48445010/send-data-from-android-activity-to-react-native?rq=1
WritableMap uriMap = Arguments.createMap();
uriMap.putString("url", uri.toString());
if(reactContext != null) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("url", uriMap);
// If there's no context, create a listener to wait for it
} else {
reactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
#Override
public void onReactContextInitialized(ReactContext context) {
context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("url", uriMap);
reactInstanceManager.removeReactInstanceEventListener(this);
}
});
}
}
}
I have a problem in my flutter app. I want to start my app on startup for android.
I use the codes, It is working very good on Android 8 and Android 9 but It is not working on Android 10
my receiver class
Ho do I have do
package com.arge24.assistant24_mobile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.util.Log;
import android.widget.Toast;
import android.content.pm.PackageManager;
import android.net.Uri;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import com.arge24.assistant24_mobile.MainActivity;
public class BootCompleteReceiver extends BroadcastReceiver {
private static final String TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message = "Service will be start. Please wait ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);
if (Intent.ACTION_BOOT_COMPLETED.equalsIgnoreCase(intent.getAction())) {
startServiceByAlarm(context);
}
}
private void startServiceByAlarm(Context context) {
// Get alarm manager.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Create intent to invoke the background service.
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
long intervalTime = 600 * 1000;
String message = "app activied... ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
// Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// Create repeat alarm.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
}
}
I used this codes in BootCompleteReceiver class but my problem did not change
Intent thisIntent = new Intent(context, MainActivity.class);
thisIntent.setAction("android.intent.action.MAIN");
thisIntent.addCategory("android.intent.category.LAUNCHER");
thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(thisIntent);
My manifest file like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.arge24.assistant24_mobile">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" tools:ignore="ProtectedPermissions" />
<application android:name="io.flutter.app.FlutterApplication" android:label="Assistant 24" android:allowBackup="false" android:icon="#mipmap/ic_launcher" android:roundIcon="#mipmap/ic_launcher_round" android:usesCleartextTraffic="true">
<activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="#style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" android:showWhenLocked="true" android:turnScreenOn="true">
<meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="#style/NormalTheme" />
<meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="#drawable/launch_background" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="BootCompleteReceiver" android:enabled="true" android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.REBOOT" />
</intent-filter>
</receiver>
</application>
</manifest>
I'm trying to get the FCM registration token or the device token in short to send push notifications to my application from my server.
The thing is I tried to get it like the code shown below but nothing happens even after uninstalling and reinstalling the apps. I'm already made sure that my Tag manager is working and also all the services needed already set in AndroidManifests.xml.
For information, I already test the Push Notifications from the firebase site and it's working just fine. But that's not what I'm aiming for. I don't understand why I can send the notifications from Firebase but can't see/acquire the FCM registration token on my Android Studio console. Is there something I missed here. I'm a beginner in this kind of thing and have been stucked with this problem for about 1 week already and at my wits end here. Hope somebody can help me. Thanks in advance for your time.
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIdService";
public String tok;
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// Instance ID token to your app server.
//sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
AndroidManifests.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asii_developer.asiisupport">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="#mipmap/planete"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/planete"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
<service
android:name=".DeviceToken">
<intent-filter>
</intent-filter>
</service>
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorPrimary" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".PageBienvenueActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PagedAccueilActivity" />
<activity android:name=".FormActivity" />
<activity android:name=".RecapActivity" />
<activity android:name=".PageDeConnexion" />
<activity android:name=".mot_de_passeActivity" />
<activity
android:name=".Liste_des_ticketsActivity"
android:windowSoftInputMode="stateHidden|adjustPan" />
<activity
android:name=".ConversationActivity"
android:windowSoftInputMode="stateHidden|adjustPan" />
<activity android:name=".NotificationsActivity">
<intent-filter>
<action android:name="notifActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="com.google.Firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".FirebaseIDService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.google.Firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
MyFireBaseMessagingService.xml
package com.example.asii_developer.asiisupport;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
Intent intent = new Intent(this, NotificationsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,
intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.arrow)
.setContentTitle("Message")
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
}
}
Try this:
// [START refresh_token]
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
Toast.makeText(this, "Refreshed token: " + refreshedToken, Toast.LENGTH_LONG).show();
// Implement this method to send token to your app's server
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
And one more thing:
You need to call sendRegistrationToServer() method which will update
token on server, if you are sending push notifications from server.
NOTE:
New Firebase token is generated (onTokenRefresh() is called) when:
The app deletes Instance ID
The app is restored on a new device
Theuser uninstalls/reinstall the app
The user clears app data.
Hope this helps! Good luck!
You need to call FirebaseInstanceId.getToken() first (probably in your MainActivity or any corresponding initial activity.
onTokenRefresh() only triggers later in the beginning if and only if the initial call to FirebaseInstanceId.getToken() return null. As mentioned in the FCM docs:
The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.
I'm trying to develop android app for that can record phone calls. So, in the initial step, I've to see if BroadcastReceiver is getting fired or not.
I've added permissions, receiver tag in AndroidManifest file. I'm testing on OnePlus X. Activity is gets started but BroadcastReceiver doesn't get fired when I get call. What's going wrong here?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name="com.example.myapp.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>
PhoneStateReceiver.Java
package com.example.myapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class PhoneStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
The permission READ_PHONE_STATE is a dangerous permission, if you are on a marshmallow device you must request runtime permission else your broadcast receiver will not work neither it will throw an error.
That is the most likely the cause of issue from your code because you have correctly registered in the Intent filter other than that there is nothing wrong as it is just a broadcast receiver and should work, i.e get called by the Android system.
hello my problem is this .
I have an Android app that receives dotifiche for Google Cloud Messaging , until the screen of the phone is turned receive notifications , but as soon as I turn it off not getting anything , ye shall public code, for now you have some ideas ?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lucabigoni.progettoclientserverolbia" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission
android:name="com.example.lucabigoni.progettoclientserverolbia.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.lucabigoni.progettoclientserverolbia.C2D_MESSAGE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<uses-permission android:name="android.permission." />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Activity.SplashScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.Prova"
android:label="#string/ciao" >
</activity>
<activity
android:name=".Activity.MainActivity"
android:label="main" >
</activity>
<activity
android:name=".Activity.manu"
android:label="#string/title_activity_manu" >
</activity>
<activity
android:name=".Activity.Visualizza"
android:label="#string/title_activity_visualizza" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyADrZavHTaGfd8_pTyqOMQLMQg2jfJT_S4" />
<activity
android:name=".Activity.mapOlbia"
android:label="#string/title_activity_map_olbia" >
</activity>
<activity
android:name=".Activity.Immagine_nave"
android:label="#string/title_activity_immagine_nave" >
</activity>
<activity
android:name=".Activity.Splash_Scree_caricamento_Immagine"
android:label="#string/title_activity_splash__scree_caricamento__immagine" >
</activity>
<activity
android:name=".Activity.Splash_screen_caricamento_dati"
android:label="#string/title_activity_splash_screen_caricamento_dati" >
</activity>
<activity
android:name=".Activity.AscoltoNave"
android:label="#string/title_activity_ascolto_nave" >
</activity>
<activity
android:name=".Activity.Scegli"
android:label="#string/title_activity_scegli" >
</activity>
<activity
android:name=".Activity.SceltaTipologia"
android:label="#string/title_activity_scelta_tipologia" >
</activity>
<receiver
android:name=".ricevitorenotifiche.NotificationReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.android.recognition" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="it.html.googleservices.push" />
</intent-filter>
</receiver>
<intentservice
android:name=".ricevitorenotifiche.GcmIntentService"
android:enabled="true"
android:exported="false"
android:process=":questo" >
</intentservice>
<receiver
android:name=".ricevitorenotifiche.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.thanksandroid.example.gcmdemo" />
</intent-filter>
</receiver>
</application>
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Explicitly specify that GcmIntentService will handle the intent.
Log.e("Ricevuto","CIAO SONO PRONTO");
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
package com.example.lucabigoni.progettoclientserverolbia.ricevitorenotifiche;
import com.example.lucabigoni.progettoclientserverolbia.Activity.MainActivity;
import com.example.lucabigoni.progettoclientserverolbia.R;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
public class GcmIntentService extends IntentService /*implements WakefulBroadcastReceiver */{
Context context;
public static int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public static final String TAG = "GCM Demo";
public GcmIntentService() {
super("GcmIntentService");
// TODO Auto-generated constructor stub
}
/*
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}*/
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
String msg = intent.getStringExtra("message");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
Log.e("qua arrivato","qua");
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
//sendNotification("Received: " + extras.toString());
sendNotification(msg);
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Log.e("qua arrivato","qua2");
Intent myintent = new Intent(this, MainActivity.class);
myintent.putExtra("message", msg);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
myintent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
NOTIFICATION_ID++;
}
}