How to execute some event if RN has been killed? - android

Not sure if I understand correctly but according to this link
Deliver silent notifications and wake up your app in the background on the user's device.
It sounded to me that it's possible to perform some action even if the app has been killed.
Currently I'm using OneSignal as below:
OneSignal.addEventListener('received', this.onReceived);
onReceived(store, notification) {
store.dispatch(receivedNotification({ notification }));
}
However the above will only be able to dispatch action if the app is in background or foreground, but once the app been killed, despite receiving notification successfully, onReceived event will not be fired.
So my question is whether is it possible to "wake" my RN app in the background and dispatch a redux action?

There is no event that you can catch before app is killed. You also cannot prevent the user from killing your app. And once it is killed you cannot 'wake' it up, as your code is not running. You can only do such tasks when the app is in the background/foreground.

Yes, it is possible you can execute some event if RN has been killed.
now the question is how basically I am also using react-native and I have got some challenges also, I also want to execute some event if RN has been killed, but I did not get any answer actually my concern is to open an app which can and show a call screen when calling notification is received so I dig a lot and I found a solution,
first I created a bridge connection between javascript to java and then write a wakeful service which gets called every time when we receive notification and then I call my background intent service and in this service I wake up my activity and set some flags which help me to open screen when screen is lock depends on the conditions
// receiver Service //
public class MessagingService extends WakefulBroadcastReceiver {
private static final String TAG = "FirebaseService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, String.valueOf(!isAppOnForeground(context)));
if (intent.getExtras() != null) {
if (!isAppOnForeground((context))) {
//This get called every time you receive notification
}
}
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}

Related

android, how to tell whether the app is in killed state by packagename

Having an android app which has service running to listen to the FCM notification.
By app in killed state I mean when swipe off the app from the recent activist app list, or close the app by tapping on the home button, or backpress on the app until the app closes (after all activities are popped out from backstack), or for any reason the OS killed the app.
There are functions could be used with the app's packagename to get some app's state info.
this one can help to tell the app is in background, but may not be killed.
public class ArchLifecycleApp extends Application implements LifecycleObserver {
#Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
//App in background
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
// App in foreground
}
}
this one can tell app is in FG only:
boolean isAppInFG(Context appContext, String packageName) {
boolean appInFG = false;
ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses != null) {
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName.equals(packageName)) {
appInFG = true;
break;
}
}
}
return appInFG;
}
after pressed home button, or swipe out the app from the recent application list, the appProcess.importance is always 300 and is same as if the app is in background (covered by other app).
Question: in this case is there way to tell the app is killed (not just simply in background)?
In a comment you wrote:
I want to determine: should the app go through a fresh re-launch (app
is killed) or just bring the app to front?
If you use a "launch Intent", this will handle all of this for you. If the app is already running, it will just bring the app to the foreground in whatever state it was in. If the app is not running, it will launch the app fresh.
To get a "launch Intent", you can use PackageManager.getLaunchIntentForPackage()

Controlling background service from another instance of an app

I made an application that fires a long-lived background service. Sometimes the application itself is closed, and the service keeps running, which is the way I want it.
The problem is that I don't know how to control that service after the caller application is closed. For example if the users re-opened the app, I'd like to give them the option whether to kill that process or keep it running.
I am able to detect if the service is running by using the following function (taken from this solution):
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I tried then calling this line from the activity, but that didn't do anything:
if(isMyServiceRunning(MyService.class)) {
stopService(new Intent(this, MyService.class));
}

Check application is minimized/background

I am so surprised!
Because not able identify application currently in foreground or background,
when i pressed home button and my application is not in foreground. then after i have used to check application running in foreground or not.
public boolean isAppOnForeground()
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) { return false; }
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses)
{
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; }
}
return false;
}
it will returns always true even if my application actually not in foreground.
Note:
My application have 2 services,
1 service will be canceled when application is removed from recent task list( that i have achieved.)
2 service will be canceled when application goes in background. (that is check wifi signal strength.)
how to know app is foreground or background?
how to stop service when application is not in foreground?
Rely on Activity callback methods, such as onPause(), onStop() and onResume(), that will give you hints on the current state of Activity. The Activity reference gives a very broad explanation of every of those methods.
try handling onpause() event of activity class. Onpause is called when activity goes out of focus.

Android NotificationListenerService throws DeadObjectException

I have a simple NotificationListenerService implementation to test the new 4.3 API. The Service itself used to work. After that, I added the sending of a broadcast when a notification of a particular package is added. Now, as soon as I start the service, it throws a DeadObjectException. This is the stack trace:
E/NotificationService﹕ unable to notify listener (posted): android.service.notification.INotificationListener$Stub$Proxy#42c047a0
android.os.DeadObjectException
at android.os.BinderProxy.transact(Native Method)
at android.service.notification.INotificationListener$Stub$Proxy.onNotificationPosted(INotificationListener.java:102)
at com.android.server.NotificationManagerService$NotificationListenerInfo.notifyPostedIfUserMatch(NotificationManagerService.java:241)
at com.android.server.NotificationManagerService$2.run(NotificationManagerService.java:814)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at com.android.server.ServerThread.run(SystemServer.java:1000)
This is how I start the Service
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_start_service:
startService(new Intent(this, ConnectService.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I can verify that the Service starts, because I do a Log on it's onCreate() and onDestroy().
And here is how the posting of notifications is handled, if it's needed:
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG, sbn.getNotification().toString());
if (sbn != null && sbn.getPackageName().equalsIgnoreCase(PKG)) {
Intent intent = new Intent(ConnectService.NOTIFY);
intent.putExtra("notification", sbn.getNotification().toString());
bManager.sendBroadcast(intent);
}
}
The thing that sucks is that the stack trace is of no use. What's going wrong?
Try not starting the service yourself. If you have enabled the NotificationListenerService in the security settings, the system should bind to it automatically.
Alternatively, check your crash logs to see if your service crashed or its process was killed. I believe there is a bug where if your NotificaitonListerService dies, the system will not rebind until you restart your phone or toggle the notifications permission in security settings.
I would like to share my answer due the info I collected from different topics in stackoverflow and my own tests. If your NotificationListenerService fails (exception, like IllegalStateException), the system will kill it and not restore it again. You can see that in the logcat:
592-592/? E/NotificationService﹕ unable to notify listener (posted): android.service.notification.INotificationListener$Stub$Proxy#4291d008
android.os.DeadObjectException
....
If the user goes to Security, Notifications, disable and enable your app, it is still not working. Why? Because it will only by restarted if the user restart the phone or if the user re-enable the option BUT going thru your app using:
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
So we need to check two things, first if the option is enabled:
private boolean checkNotificationSetting() {
ContentResolver contentResolver = getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
String packageName = getPackageName();
return !(enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName));
}
If it is enabled, we check if the service is Death:
private boolean isNLServiceCrashed() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> runningServiceInfos = manager.getRunningServices(Integer.MAX_VALUE);
if (runningServiceInfos != null) {
for (ActivityManager.RunningServiceInfo service : runningServiceInfos) {
//NotificationListener.class is the name of my class (the one that has to extend from NotificationListenerService)
if (NotificationListener.class.getName().equals(service.service.getClassName())) {
if (service.crashCount > 0) {
// in this situation we know that the notification listener service is not working for the app
return true;
}
return false;
}
}
}
return false;
}
What is this service.crashCount ? Documentation says:
Number of times the service's process has crashed while the service is running.
So if its more than 0, it means it's already death. Therefore, in both cases, we have to warning the user and offer the possibility to restart the service using the intent I posted before:
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
Of course, if the service crashes, it will be good to detect why and when to prevent it too.

Toggle Service Activity

I'm developing a service that need to run foreground, and users can toggle it on/off through an activity. So basically, the activity MAY be killed, but the service is safe as long as it is not stopped by user.
However, I'm getting this trouble: how to turn off the service if it is on? That mean, if my activity was killed, then restarted, so I get no reference of the started service intent to call stopService.
Below is my current code. It works fine if the user call deactivate after the service is started by the same activity. The button status is always correct, but when my activity is restarted by the OS, this.serviceIntent is null.
protected boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (SynchronizationService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onResume() {
super.onResume();
this.togglingByCode = true;
this.butActivate.setChecked(this.isServiceRunning());
this.togglingByCode = false;
}
public void onActivateButtonClick(final boolean pIsChecked) {
if (this.togglingByCode) { return; }
if (pIsChecked) {
this.saveSettings();
this.serviceIntent = new Intent(this, SynchronizationService.class);
this.serviceIntent.putExtra(KEY_WEBSERVICE, this.txtWebService.getText().toString());
this.serviceIntent.putExtra(KEY_PASSWORD, this.txtPassword.getText().toString());
this.serviceIntent.putExtra(KEY_INTERVAL, Integer.parseInt(this.txtRefreshInterval.getText().toString()));
this.serviceIntent.putExtra(KEY_TIMEOUT, this.preferences.getInt(KEY_TIMEOUT, DEFAULT_TIMEOUT));
this.serviceIntent.putExtra(KEY_RETRY, this.preferences.getInt(KEY_RETRY, DEFAULT_RETRY));
this.startService(this.serviceIntent);
} else {
this.stopService(this.serviceIntent);
this.serviceIntent = null;
}
}
Please tell me how to stop the service correctly. Thank you.
P.s: I know a trick that make serviceIntent static, but I don't feel safe about it. If there is no any other way, then I will use it.
Simply initialize your serviceIntent in the activity's onCreate... You can start your service, kill your activity, reopen it and stop the service with the same serviceIntent.

Categories

Resources