简体   繁体   English

当活动崩溃时会发生什么?

[英]What happen when the activity crash?

I have a service created like this : 我有一个像这样的服务:

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

Then I implement the onBind like this: 然后我像这样实现onBind

  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: the Activity binds to the Service and sets up a listener. 这很简单:Activity绑定到Service并设置一个监听器。 When the Service receives a message it simply fires the listener 当服务收到消息时,它只是触发监听器

Now the big question: what happen if the activity crash suddenly? 现在最大的问题是: 如果活动突然崩溃会发生什么? In that case mListener will point to something non-existent, no? 在那种情况下, mListener将指向一些不存在的东西,不是吗?

How, before calling mListener.onMessageReceived(remoteMessage) , can I check to see if the bound Activity is still alive ? 在调用mListener.onMessageReceived(remoteMessage) ,我可以检查绑定的Activity是否还活着吗?

You can use a WeakReference and DeadObjectException since your Activity seems to be in another app. 您可以使用WeakReferenceDeadObjectException,因为您的Activity似乎在另一个应用程序中。 This will allow you to know if the Activity was garbage collected because your reference will become null and you will not leak. 这将允许您知道Activity被垃圾收集,因为您的引用将变为null并且您不会泄漏。

private WeakReference<MyListener> mListener;

This is how you store the WeakReference . 这就是你存储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.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM