...">

What happens when activity crashes?

I have a service created as follows:

<service android:name="com.myFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> 

Then I implement onBind as follows:

  private final IBinder mBinder = new LocalBinder(); private myListener mListener; public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } } public void setListener(myListener listener) { mListener = listener; } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onMessageReceived(RemoteMessage remoteMessage) { if (mListener != null) mListener.onMessageReceived(remoteMessage); } 

It is quite simple: Activity is attached to the Service and sets the listener. When a service receives a message, it simply starts a listener

Now the big question is: what happens if activity suddenly fails? In this case, mListener will point to something non-existent, no?

How, before calling mListener.onMessageReceived(remoteMessage) , can I check if the associated activity is still maintained?

+5
source share
1 answer

You can use WeakReference and DeadObjectException , since your Activity seems to be in a different application. This will let you know if the Activity collected garbage because your link will become null and you will not leak.

 private WeakReference<MyListener> mListener; 

This is how you store WeakReference .

 public void setListener(MyListener listener) { mListener = new WeakReference<MyListener>(listener); } 

This is how you use it.

 @Override public void onMessageReceived(RemoteMessage remoteMessage) { MyListener listener = mListener.get(); if(listener != null) { try { listener.onMessageReceived(remoteMessage); } catch(DeadObjectException exception) { } } else { // Activity was destroyed. } } 
+2
source

Source: https://habr.com/ru/post/1267040/


All Articles