I'm trying to send a push notification to all devices from firebase but at first i tried only in my phone, it doesn't work, after that i tried in another phone and it doesn't work either. Finally with the 3rd one it work and it work at the second one magically. What i have to do to the push notifications work in all devices?
Manifest ->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.startingandroid.firebasecloudmessaging">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity" android:label="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" android:label="FCM"></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>
</application></manifest>
MyFirebaseInstanceIDService ->
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token in logcat
Log.e(TAG, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
} }
MyFirebaseMessagingService ->
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "StartingAndroid";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//It is optional
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
//This method is only generating push notification
private void sendNotification(String title, 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);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
SplashActivity
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}, 4000);
}}
Related
How can I keep the foreground service running even when the user quits the app?
I've tried running the service in another process, but the service still stops after I quit the app.
My AndroidManifest.xml:
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Test"
tools:targetApi="31">
<service
android:name=".Service"
android:enabled="true"
android:process=":service"
android:exported="false" />
<activity
android:process=":activity"
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Service.java:
public class CountdownService extends Service {
NotificationManager notificationManager;
private String createNotificationChannel(String channelId, String channelName) {
NotificationChannel chan = new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(chan);
return channelId;
}
NotificationCompat.Builder builder;
#NonNull
private Notification getNotification() {
String channelId = createNotificationChannel("id", "name");
builder = new NotificationCompat.Builder(this, channelId);
return builder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.setContentText("Content Text")
.setSubText("Sub Text")
.setContentTitle("Content Title")
.build();
}
#Override
public void onCreate() {
super.onCreate();
startForeground(1, getNotification());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And in MainActivity, I start the service like this:
Intent intent = new Intent(this, Service.class);
startForegroundService(intent);
I found that this application has only one process 'service' in the phone settings, but there is no 'activity' process, what is the problem? thanks.
Define what you mean by "exit." If you mean they go into recents and swipe the app away, or go into settings and force quit, no. That's the user saying "I want this app to end". That will kill all services. Something that could run even when the user says it shouldn't is basically malware.
I have to launch the app on receiving notifications. The following piece of code works fine when the app is killed and notification is received. But I want When Notification received App Open Automatically Without Click On Notification. App Lunch Automatically in all cases if my mobile is locked too.
Please Help Me. Here Is My Code.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private static final String TAG="PushNotification";
private static final String CHANNEL_ID = "101";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
subscribeToTopic();
getToken();
}
private void getToken()
{
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if(!task.isSuccessful()){
Log.d(TAG,"OnComplete: Faileed to get the Token");
}
String token=task.getResult();
Log.d(TAG, "onComplete: " + token);
}
});
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "firebaseNotifChannel";
String description = "Receve Firebase notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private void subscribeToTopic() {
FirebaseMessaging.getInstance().subscribeToTopic("resulttime")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
});
}
}
MyFireBaseServices.java
public class MyFirebaseServices extends FirebaseMessagingService {
private static final String TAG ="PushNotification";
private static final String CHANNEL_ID = "101";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
showNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
private void showNotification(String title,String message){
Intent intent = new Intent(this, Result.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_24)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.link.fcmpuchtest">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.FcmPuchTest">
<activity android:name=".Result"
android:parentActivityName=".MainActivity">
</activity>
<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=".MyFirebaseServices">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
My Php Code Is
<?php
function notify($to,$data){
$api_key="AAAAjW65hDI:APA91bE4cXuCdMf9pPDVHqjjpjelkjirj']9099hUqOX0SOXzi5GEc3mdPwRqsG8bgqz0S3EnpoQtWCaj2_wbF39I57Tyxo4EAeJ2pSo_IVJPc_fQp7hiuNFGYTjkbnJHUIOK7HTioU";
$ch = curl_init();
$url="https://fcm.googleapis.com/fcm/send";
$fields=json_encode(array('to'=>$to,'notification'=>$data));
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($fields));
$headers = array();
$headers[] = 'Authorization: key ='.$api_key;
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
}
$to="/topics/resulttime";
$data=array(
'title'=>'Greetings Result',
'body'=>'Hi, From PHP Script'
);
notify($to,$data);
echo "Notification Sent";
?>
I have Already Use This Code But Not Working
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
startActivity(new Intent(this, MainActivity.class));
}
}
I am building basic calling app using TelecomManager, ConnectionService and Connection. But, When an there is an incoming call, my incomingActivity UI is not showing up. Below is the sample code so far.
In my MainActivity.java
Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
startActivity(intent);
// ================================================================
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
// new ComponentName(getPackageName(), CallHandler.TAG), "myCallHandlerId");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
new ComponentName(getApplicationContext(), CallHandler.TAG), "myCallHandlerId");
PhoneAccount phoneAccount = PhoneAccount
.builder(phoneAccountHandle, "myCallHandlerId")
.setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
.build();
manager.registerPhoneAccount(phoneAccount);
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle));
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle).isEnabled());
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle).getClass());
Log.i("Phone Account isEnabled", "" + phoneAccount.isEnabled());
Bundle bundle = new Bundle();
Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, "555555555", null);
bundle.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, uri);
bundle.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
// manager.addNewIncomingCall(phoneAccountHandle, bundle);
Log.i("Permitted", "" + manager.isIncomingCallPermitted(phoneAccountHandle));
if(manager.isIncomingCallPermitted(phoneAccountHandle)){
Log.i("Call", "Incoming");
manager.addNewIncomingCall(phoneAccountHandle, bundle);
}
}
In my CallHandler.java
#RequiresApi(api = Build.VERSION_CODES.M)
public class CallHandler extends ConnectionService{
public static final String TAG = CallHandler.class.getName();
#RequiresApi(api = Build.VERSION_CODES.N_MR1)
#Override
public Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i("CallHandler","onCreateIncomingConnection");
// return super.onCreateIncomingConnection(connectionManagerPhoneAccount, request);
Context context = getApplicationContext();
Log.i("Context","" + context);
Log.i("Context","" + context.getPackageName());
Log.i("Context","" + getBaseContext());
Log.i("Context","" + context.getClass().getName());
Log.i("Context","" + context.getClass().getSimpleName());
CallConnection callConnection = new CallConnection(context);
callConnection.setInitializing();
callConnection.setActive();
callConnection.setCallerDisplayName("Manik", TelecomManager.PRESENTATION_ALLOWED);
// callConnection.setConnectionProperties(Connection.PROPERTY_SELF_MANAGED);
// callConnection.setConnectionCapabilities(Connection.CAPABILITY_HOLD & Connection.CAPABILITY_SUPPORT_HOLD);
return callConnection;
}
#Override
public void onCreateIncomingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
return super.onCreateOutgoingConnection(connectionManagerPhoneAccount, request);
}
}
In my CallConnection.java
#RequiresApi(api = Build.VERSION_CODES.M)
public class CallConnection extends Connection {
private Context context;
#RequiresApi(api = Build.VERSION_CODES.N_MR1)
public CallConnection(Context con) {
context = con;
setConnectionProperties(PROPERTY_SELF_MANAGED);
setAudioModeIsVoip(true);
}
#Override
public void onAnswer(int videoState) {
super.onAnswer(videoState);
Log.i("Call","Answered");
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onShowIncomingCallUi() {
Log.i("Call","Incoming Call");
super.onShowIncomingCallUi();
// MainActivity con = new MainActivity();
// Context context = con.getApplicationContext();
NotificationChannel channel = new NotificationChannel("channel", "Incoming Calls",
NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
// other channel setup stuff goes here.
// We'll use the default system ringtone for our incoming call notification channel. You can
// use your own audio resource here.
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
channel.setSound(ringtoneUri, new AudioAttributes.Builder()
// Setting the AudioAttributes is important as it identifies the purpose of your
// notification sound.
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
// NotificationManager mgr = context.getSystemService(NotificationManager.class);
// mgr.createNotificationChannel(channel);
// Create an intent which triggers your fullscreen incoming call user interface.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, IncomingCallScreenActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);
Log.i("Intent1","" + intent);
Log.i("Intent2","" + intent.getPackage());
Log.i("Intent3","" + intent.getType());
Log.i("Intent4","" + intent.getData());
Log.i("Intent5","" + intent.getDataString());
Log.i("Intent6","" + intent.getAction());
Log.i("Intent7","" + intent.getCategories());
Log.i("Intent8","" + intent.getExtras());
Log.i("Pending Intent","" + pendingIntent);
Log.i("Pending Intent","" + pendingIntent.getCreatorPackage());
// Build the notification as an ongoing high priority item; this ensures it will show as
// a heads up notification which slides down over top of the current content.
final Notification.Builder builder = new Notification.Builder(context);
builder.setOngoing(true);
builder.setPriority(Notification.PRIORITY_HIGH);
// Set notification content intent to take user to fullscreen UI if user taps on the
// notification body.
builder.setContentIntent(pendingIntent);
// Set full screen intent to trigger display of the fullscreen UI when the notification
// manager deems it appropriate.
builder.setFullScreenIntent(pendingIntent, true);
// Setup notification content.
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Your notification title");
builder.setContentText("Your notification content.");
// Set notification as insistent to cause your ringtone to loop.
Notification notification = builder.build();
notification.flags |= Notification.FLAG_INSISTENT;
// Use builder.addAction(..) to add buttons to answer or reject the call.
NotificationManager notificationManager = context.getSystemService(
NotificationManager.class);
notificationManager.notify("Call Notification", 37, notification);
// context.startActivity(intent);
}
}
All the log messages inside onCreateIncomingConnection() and onShowIncomingCallUi() are showing up when the app launches, and not when there is an incoming call.
All the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
<!--
Needed only if your calling app reads numbers from the `PHONE_STATE`
intent action.
-->
<uses-permission android:name="android.permission.READ_PHONE_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">
<activity android:name=".IncomingCallScreenActivity"></activity>
<activity android:name=".CallScreenActivity" />
<activity android:name=".ContactsActivity" />
<activity android:name=".LogsActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tel" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".CallHandler"
android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />
</intent-filter>
</service>
</application>
Any help would be appreciated. Thanks
I am trying to make an android application where I receive notification using firebase. I followed resources available over the internet.
All I want to do is send notification from firebase, the message that I receive I want to display it in TextView in main activity.
Currently I am testing in an emulator. There are few problems that I am not able to resolve.
I am able to send notification from firebase but:
When the application is running in foreground I don't receive a notification in the android notification panel and nothing happens in the main activity too. That is the text in TextView does not change.
When the application is running in background I do receive the notification in android notification panel with message sent from firebase, clicking the notification main activity opens but the text in TextView does not change.
Firebase Messaging Service
public class VAFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "VAFirebaseMessagingS";
public VAFirebaseMessagingService() {}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("text"));
}
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
private TextView userFeedbackQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFeedbackQuery = (TextView) findViewById(R.id.pfiva_user_feedback_query);
final Intent intent = getIntent();
if(intent.hasExtra(Intent.EXTRA_TEXT)) {
String userFeedbackQueryText = intent.getStringExtra(Intent.EXTRA_TEXT);
userFeedbackQuery.setText(userFeedbackQueryText);
}
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.pfiva.mobile.voiceassistant">
<uses-permission android:name="android.permission.INTERNET" />
<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=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".messaging.FirebaseInstanceService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".messaging.VAFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
Please can someone guide what is wrong here? How can i solve the above two problems.
Thanks
After suggestions i made the below changes in Messaging Service, basically added notification channel.
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
Problem i face now is that when the app is running in background, i do receive notification in notification panel and clicking on it open main activity but the text in TextView is not updated.
Two ideas to solve your issue:
Have you register your VAFirebaseMessagingService in your AndroidManifest.xml:
Since Android 8, you must use an Notification Channel to send push notifications. Android
I have a broadcast receiver which detects oncoming notifications when the app is open and in background but when the recent app is cleared the receiver is not working please suggest me ideas.
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
JSONObject json = new JSONObject();
try {
json.putOpt("userid", StorePreference.GetSharedPreferenceDetails(context, "memberid"));
json.putOpt("rid",StorePreference.GetSharedPreferenceDetails(context, "partnerid"));
json.putOpt("message", "Received");
BoundService.getInstance().onlinestatus(json);
} catch (Exception e) {
e.printStackTrace();
}
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Manifest decleration:
<receiver
android:name="com.twogether.receivers.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name = "com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.google.android.gcm.demo.app" />
</intent-filter>
</receiver>
Try to register your receiver in manifest, use GcmListenerService to receive messages.
google example https://github.com/googlesamples/google-services has example to do this.
<!-- gcm_receiver, this is android source-->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.myapp.gcm" />
</intent-filter>
</receiver>
<!-- gcm_listener service -->
<service
android:name="com.qblinks.qmote.GcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
// Use this service to receive message
public class GcmListenerService extends com.google.android.gms.gcm.GcmListenerService {
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.v(TAG, "From: " + from);
Log.v(TAG, "Message: " + message);
sendNotification(message);
}
private void sendNotification(String message) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification)
.setContentTitle("this is title")
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))//multi line
.setSound(defaultSoundUri); // ring or vibrate if no ring
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Const.NOTIFICATION_GCM /* ID of notification */, notificationBuilder.build());
}
}
When the app is close you need to wake the app up, means you need to have the permission to do that
<uses-permission android:name="android.permission.WAKE_LOCK" />
and after you can set:
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, yourIntent);