Android Service stops broadcasting progress after a while - java

I have an Activity where the user can download a video. Upon user's click, the Download Service starts to download the content.
There is a progress bar in the Activity UI which I would like to update according to download progress in the service which broadcasts the progress periodically.
Everything works fine but after a certain time the service stops sending any broadcast progress, hence, the UI does not update anymore.
Additionally, how I can resume receiving the progress broadcast when the user goes to another Activity and comes back to this Activity? I mean, even if the above issue is solved, when the user presses back button and go to other activity and comes back to this activity, the progress gets lots. How can I check for any existing broadcast and receive it whenever the user comes to this activity.
In the ACTIVITY:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.d("DownloadService", "Progress Received In Activity");
Double progress = bundle.getDouble("PROGRESS");
updateDownloadProgressBar(progress);
}
}
};
private void startDownloadService() {
final String videoId = mItem.getAttributes().get(KEY_ASSET_ID);
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("VIDEOID", videoId);
startService(intent);
}
in the onResume():
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION_SERVICE));
in the onPause():
unregisterReceiver(receiver);
In the SERVICE:
private void publishProgress(double progress) {
Log.d(TAG, "Broadcasting progress from Service");
Intent intent = new Intent(NOTIFICATION_SERVICE);
intent.putExtra("PROGRESS", progress);
sendBroadcast(intent);
}
The download and progress work fine to 38% then stop.

It seems that the service is being stopped/killed from the OS, to avoid that use foreground service so you can make sure it will not be killed from the OS.
See the sample code below:
Service
public class PendingService extends Service {
private final static String TAG = "PendingService";
public final static int NOTIFICATION_ID = 94;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startInForeground();
// Do your work here ...
return START_STICKY;
}
private void startInForeground() {
String NOTIFICATION_CHANNEL_ID = "default";
String NOTIFICATION_CHANNEL_NAME = "My Pending Service";
String NOTIFICATION_CHANNEL_DESC = "This notification holding a pending task";
Intent notificationIntent = new Intent(this, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
channel.setSound(null, null);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
Notification notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
removeNotification(NOTIFICATION_ID);
// ....
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void removeNotification(int notificationId) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(notificationId);
}
}
}
Utils you may need
class ServiceUtils {
/**
* #param service: Service to run
*/
fun startService(context: Context, service: Class<out Service>) {
val serviceIntent = Intent(context, service)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
}
/**
* #return True: if the service is running
*/
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}

Related

How to know os kill my foreground service android

I made a lock screen app. I want to restart my service when the OS kills the service in Xiaomi Redmi Note 10 Pro (MIUI 12). When the service is killed, onDestroy is not call.
public class LockScreenService extends Service {
SharedPreferences prefs;
private BroadcastReceiver screenStateReceiver;
public static boolean isScreenReceiverRegistered=false;
public IBinder onBind(Intent paramIntent) {
return null;
}
public void onCreate() {
super.onCreate();
prefs = getSharedPreferences("SettingPreference", Context.MODE_PRIVATE);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.setPriority(999);
screenStateReceiver = new ScreenStateReceiver();
registerReceiver(screenStateReceiver, filter);
isScreenReceiverRegistered = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = createNotificationChannel(notificationManager);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_notification)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build();
startForeground(127, notification);
}
}
#RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
String channelId = "my_service_channelid";
String channelName = "Lock Screen Running";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
// omitted the LED color
channel.setImportance(NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return START_STICKY;
}
and on onDestroy() function I restart my service.
Manifests
<service android:name=".LockScreenService"
android:process=":ServiceProcess"
android:enabled="true"
android:exported="false"/>
try this, if you want to get it in onResume()
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: GamePreferences.getPid()--------> " + GamePreferences.getPid());
Log.d(TAG, "onResume: android.os.Process.myPid()--------> " + android.os.Process.myPid());
if (GamePreferences.getPid() != 0) {
if (GamePreferences.getPid() != android.os.Process.myPid()) {
Log.d(TAG, "GamePreferences.getPid() != android.os.Process.myPid(): --------> " + android.os.Process.myPid());
//restart your service in foreground
return;
}
}
}
According to the documentation, there is no guarantee onDestroy will be called. I could not find an explicit mention to what happens when the process is killed, but it seems that you are more likely to be called onStop. So you can try to start your service with an intent from onStop.
Also, there are documented ways to prevent your process to be elected, such as: having a related Activity running or having ongoing callbacks in BroadcastReceiver or Service.
Note well that your process might get killed by the user, and refusing to comply to the user's desire to kill is invasive. Therefore the best solution should be designed around the actual reason why a user would want your process to stay alive.

How to clear the notification when the app is force closed?

Am Working on a timer based app where the notification shows up when the timer starts to run. I have set it as ongoing so that it cannot be cleared.
I have used cancelAll() method for some cases which works fine but when I force close the app, the notification still shows up and cannot be removed and tried to use the method in onDestroy() method still the problem prevails.
Here is my code and created the channel in another class :
public void sendNotif(){
Intent resultIntent = new Intent(this, TimerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
not = new NotificationCompat.Builder(this,Notif.CHANNEL_ID)
.setSmallIcon(R.drawable.curved_shape)
.setContentTitle("Productivity Timer")
.setContentText("Your Timer is Running")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setOngoing(true)
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(1,not);
}
I found this great solution once, I will retype it here
Since your application and the notification are handled in different threads, so killing your application won't kill the notification. The solution is to create a Service to kill notification, since services will restart themselves when the app is killed suddenly, you can use the automatic restart to kill the notification.
Create the service class
public class KillNotificationsService extends Service {
public class KillBinder extends Binder {
public final Service service;
public KillBinder(Service service) {
this.service = service;
}
}
public static int NOTIFICATION_ID = 666;
private NotificationManager mNM;
private final IBinder mBinder = new KillBinder(this);
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.cancel(NOTIFICATION_ID);
}
}
Add it to your manifest
<service android:name="KillNotificationsService"></service>
Always create the Service before fireing the notification, and use the static notificationid
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder binder) {
((KillBinder) binder).service.startService(new Intent(
MainActivity.this, KillNotificationsService.class));
Notification notification = new Notification(
R.drawable.ic_launcher, "Text",
System.currentTimeMillis());
Intent notificationIntent = new Intent(MainActivity.this,
Place.class);
PendingIntent contentIntent = PendingIntent.getActivity(
MainActivity.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(),
"Text", "Text", contentIntent);
NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.notify(KillNotificationsService.NOTIFICATION_ID,
notification);
}
public void onServiceDisconnected(ComponentName className) {
}
};
bindService(new Intent(MainActivity.this,
KillNotificationsService.class), mConnection,
Context.BIND_AUTO_CREATE);

How to cold start a React Native app over device lock screen?

I'm building a VoIP app on React Native, which detects incoming calls using push notifications. I need to start the app and bring it to the foreground on receiving a push notification. I'm able to achieve that for the following scenarios:
When the device is unlocked and:
The app is minimized (is still in the background)
The app is not in the background (killed from multitasking view)
When the device is locked and:
The app is minimized (is still in the background)
The only scenario I'm not able to handle is when the device is locked and the app is killed. The app starts but does not show up over the lock screen. Instead, the user needs to unlock the phone to access the app.
Here's the piece of code that runs when a notification is received,
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent notificationIntent = new Intent(this, MainActivity.class);
// Check if app is running
if(MainActivity.isAppRunning) {
startActivity(notificationIntent);
Intent messagingEvent = new Intent(MESSAGE_EVENT);
messagingEvent.putExtra("message", remoteMessage);
// Broadcast it so it is only available to the RN Application
LocalBroadcastManager
.getInstance(this)
.sendBroadcast(messagingEvent);
} else {
startActivity(notificationIntent);
try {
// If the app is in the background we send it to the Headless JS Service
Intent headlessIntent = new Intent(
this.getApplicationContext(),
BackgroundListenService.class
);
headlessIntent.putExtra("message", remoteMessage);
this
.getApplicationContext()
.startService(headlessIntent);
Log.d(TAG, "message: " + remoteMessage);
HeadlessJsTaskService.acquireWakeLockNow(this.getApplicationContext());
} catch (IllegalStateException ex) {
Log.e(
TAG,
"Background messages will only work if the message priority is set to 'high'",
ex
);
}
}
}
And here's my MainActivity:
public class MainActivity extends NavigationActivity {
public static boolean isAppRunning;
private static boolean isMessageRecieved;
private class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
isMessageRecieved=true;
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this);
super.onCreate(savedInstanceState);
isAppRunning = true;
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
// Subscribe to message events
localBroadcastManager.registerReceiver(
new MainActivity.MessageReceiver(),
new IntentFilter(MyFirebaseMessagingService.MESSAGE_EVENT)
);
if(isMessageRecieved) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "1";
String channel2 = "2";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
isAppRunning = false;
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
}

Run API every second in Background after Android App is killed in Oreo version

I am trying to Build a Android Application which will run every second and when app is closed or killed then also it should run continuously in Background.
When API response condition is satisfied it should show a Local Notification..
I have used Service Class for background Task. It was working fine in all version Except the Oreo Version (8.1v)
I have check website and Example related to it, I have find out that we can't perform background task in Oreo Version after the app is closed or killed.
So I tried to use startForeground() then also it is not working,
After many tries, finally I am asking this question here.
So please help me to run a API in Background when App is closed.
MainActivty.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(this, new Intent(this,MyService.class));
} else {
startService(new Intent(this,MyService.class));
}
}
MyService.class
public class MyService extends Service {
public static final int notify = 3000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
new ApiCallAsyncTask().execute(URL);
}
});
}
}
}
Notification Method which is called in ApiCallAsyncTask class
Notification notif;
#TargetApi(Build.VERSION_CODES.O)
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void notification(String Name, String time,String mId,int id){
Intent intent = new Intent(MyService.this, MainActivity.class);
String CHANNEL_ID = String.valueOf(id);
PendingIntent pendingIntent = PendingIntent.getActivity(MyService.this, 100, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, Name, NotificationManager.IMPORTANCE_DEFAULT);
notif = new Notification.Builder(MyService.this)
.setContentIntent(pendingIntent)
.setContentTitle("Reminder")
.setContentText("hello")
.setSmallIcon(R.drawable.logo)
.setOnlyAlertOnce(true)
.setColor(ContextCompat.getColor(MyService.this, R.color.colorPrimaryDark))
.setChannelId(CHANNEL_ID)
.build();
notificationManager.createNotificationChannel(mChannel);
}else {
notif = new Notification.Builder(MyService.this)
.setContentIntent(pendingIntent)
.setContentTitle("Reminder")
.setContentText("hello")
.setSmallIcon(R.drawable.logo)
.setOnlyAlertOnce(true)
.setColor(ContextCompat.getColor(MyService.this, R.color.colorPrimaryDark))
.build();
}
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notif);
startForeground(1, notif);
}
Thank You..
You can use combination of JobIntentService + AlarmManager(for scheduling) or JobScheduler API.
But I strongly recommend replace your approach with Firebase Cloud Messaging. So you will place business logic on server side and notify clients in special cases.

Open a different activity other than MainActivity when clicking Firebase Notification

In my application i want open custom activity (not MainActivity) and putExtra to this activity when click on Firebase notification.
I write below codes, but when click on notification open MainActivity, But i want open my another activity (AuctionDetailActivity).
My NotificationManager class :
public class MyNotificationManager {
private Context mCtx;
private Uri soundUri;
private static MyNotificationManager mInstance;
public MyNotificationManager(Context context) {
mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body) {
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(mCtx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("fcm_notification", "Y");
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setContentText(body)
.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mNotifyMgr.notify(1, mBuilder.build());
}
}
}
And MyFirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotify(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
}
private void showNotify(String title, String body) {
MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
//myNotificationManager.displayNotification(title, body);
myNotificationManager.displayNotification(title, body);
}
}
MainActivity codes:
#Override
protected void onResume() {
super.onResume();
String fcm_notification = getIntent().getStringExtra("fcm_notification");
Log.d("FireBaseIntentLog", " FCM : " + fcm_notification);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d("FireBaseIntentLog", "Key: " + key + " Value: " + value + " FCM : " + fcm_notification);
}
}
}
How can i fix it?
If you are sending the notification from Firebase console or inside the notification field using FCM API, the app behaves in two ways -
If your app is in foreground, the method onMessageReceived of your FCM service class will be called.
If your app is in background, nothing will happen inside your FCM service class. Rather, the notification will be handled internally by the FCM library itself and the notification with launcher activity in the intent will be shown.
And if you use FCM API to send notification and use the data field, the library does nothing itself and instead calls the method onMessageReceived regardless of whether your app is in foreground or background.
So in order to solve your issue, you can use one of the following two solutions:
Use FCM API to send notifications and use the data field instead of the notification field. Check the documentation to read more about FCM API.
In your launcher (main) activity, check for intent inside onCreate and if it is coming from notification, read the extras, finish the main activity and open your required activity.
Example for second case:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkIntent()) return;
// other code.
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent();
}
private boolean checkIntent() {
// to receive the value, send the value as custom data from Firebase console.
String value = getIntent().getStringExtra("your_key");
if (value == null) return false;
if (value.equals("something")) {
// open one activity.
} else if (value.equals("another_thing")) {
// open another activity.
}
finish();
return true;
}
Change this below line
Intent intent = new Intent(click_action);
to this
Intent intent = new Intent(getActivity(), YourClass.class);
You just need modify in sendNotification function
public void sendNotification(String messageBody, String messageTitle, int user_id, String click_action) {
Intent intent = new Intent(mCtx, AuctionDetailActivity.class); // Need modify this line
intent.putExtra(Extras.bidID.name(), user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
Change your MyFirebaseMessagingService class as shown below replace OtherApp.class with your activity name
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent=new Intent(this,OtherApp.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);//newbg PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder= new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("FCM NOTIFICATION"); notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}

Categories