[英]How to call a method in an Activity from another class
我正在开发一个SMS应用程序,并且在MainActivity
有一个方法可以执行按钮单击:
public void updateMessage() {
ViewMessages.performClick();
}
当我从MainActivity
类内部调用此方法时,此方法可以正常工作并执行按钮单击。
但是,当我从如下所示的任何其他类中调用此方法时,从IntentServiceHandler
类中调用Main Activity的updateMessage
方法,则得到了NullPointerException
:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'boolean android.widget.Button.performClick()'
public class IntentServiceHandler extends IntentService {
public IntentServiceHandler() {
super("IntentServiceHandler");
}
@Override
protected void onHandleIntent(Intent intent) {
String message = intent.getStringExtra("message");
TransactionDataBase transactionDB = new TransactionDataBase(this, 1);
transactionDB.addMessage(message);
MainActivity mainActivity = new MainActivity();
mainActivity.updateMessage();
}
}
我该如何处理?
编辑:我什至试图使updateMessage方法静态,现在我得到以下异常
android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。
不要在IntentService中调用Activity方法,请尝试使用Intent在Activity和IntentService之间进行通信。
将最后两个语句onHandleIntent()替换为
Intent intent = new Intent(); broadcastIntent.setAction(MainActivity.UPDATE_MESSAGE); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); sendBroadcast(intent);
并且您应该在MainAcitivty的onCreate()中注册一个BroadcastReceiver,例如
private BroadcastReceiver receiver; @Override public void onCreate(Bundle savedInstanceState){ // .... IntentFilter filter = new IntentFilter(); filter.addAction(UPDATE_MESSAGE); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // do something based on the intent's action // for example, call updateMessage() } }; registerReceiver(receiver, filter); }
IntentService的onHandleIntent在另一个线程(而不是主线程/ ui线程)中运行,因此不允许在onHandleIntent中更新UI组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.