我要做的是将对mainactivity的引用传递给另一个类并使用它。
当我第一次传递引用时,它不是null。但后来当我在事件处理程序中使用它时,它变为null。
这是代码:
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();
}
}
我获得参考的另一个类:
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);
}
}
答案 0 :(得分:1)
如果你
,它只会“变为”空答案 1 :(得分:1)
您没有注册SmsReceiver,因此我想以下内容:
SmsReceiver已在Manifest中注册。因此,接收器的实例是在检测到广播时由系统创建的,并且它与您创建的实例不同。
建议:在活动中注册接收者,而不是在清单中注册。