Android: Reference to Activity object in another c

2019-07-18 02:41发布

问题:

What i am trying to do is to pass a reference to the mainactivity to another class and use it.

when i first pass the reference it is not null. but later when i use it in an event handler it becomes null.

here is the code:

public class MainActivity extends MapActivity implements SmsReceivedListener {
    SmsReceiver smsreceiver = new SmsReceiver();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        smsreceiver.setSmsReceivedListener(this);
    }

    public void drawme() {
        // do smth
    }

    @Override
    public void onSmsReceived(String id, String lon, String lat) {
        Toast.makeText(this, "SMS delivered", Toast.LENGTH_LONG).show();

    }
}

The other class where I obtain the reference:

public class SmsReceiver extends BroadcastReceiver {
    private SmsReceivedListener listener;
    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    @SuppressLint("NewApi") 
    @Override
    public void onReceive(final Context context, final Intent intent) {
        // Here it is NULL
        if(listener!=null)
            listener().onSmsReceived(carNumber, lon,lat);
    }

    public void setSmsReceivedListener(SmsReceivedListener mainActivity) {
        //It is no null when I first set the object here
        listener = (mainActivity);
    }
}

回答1:

It will only "become" null if you

  • set it to null
  • use it in a way which is not thread safe and you are reading in a different thread to setting
  • you are using the same field, but in a different object.


回答2:

You are not registering the SmsReceiver, therefor i guess the following :

The SmsReceiver is registered in the Manifest. Therefore, an instance of the receiver is created by the system when the broadcast is detected, and it is not the same instance as the one you create.

Suggestion : register the receiver in the activity, not in the manifest.