如何从另一个类调用Activity中的方法

时间:2016-11-13 06:18:08

标签: java android nullpointerexception

我正在开发一个SMS应用程序,我在MainActivity中有一个方法来执行按钮点击:

public void updateMessage() {
    ViewMessages.performClick();
}

当我从MainActivity类中调用此方法时,此方法正常工作并执行按钮单击 但是,当我从任何其他类调用此方法时,如下所示,我从updateMessage类调用主活动的IntentServiceHandler方法,我得到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:只有创建视图层次结构的原始线程才能触及其视图。

1 个答案:

答案 0 :(得分:1)

不要在IntentService中调用Activity的方法,尝试使用Intent在Activity和IntentService之间进行通信。

  1. 使用

    替换onHandleIntent()的最后两个语句
    Intent intent = new Intent();
    broadcastIntent.setAction(MainActivity.UPDATE_MESSAGE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    sendBroadcast(intent);
    
  2. 你应该在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);
    } 
    
  3. onHandle IntentService的内容在另一个线程(而不是主线程/ ui线程)中运行,因此不允许在onHandleIntent中更新UI组件。

相关问题