安卓的BroadcastReceiver的onReceive更新的TextView在MainActivityonReceive、BroadcastReceiver、MainActivity、TextV

由网友(渡河已尽生)分享简介:在MainActivity我有一个TextView:textV1。我也有在MainActivity一个方法来更新的TextView的:In MainActivity I have a TextView: textV1. I also have a method in MainActivity that update...

在MainActivity我有一个TextView:textV1。我也有在MainActivity一个方法来更新的TextView的:

In MainActivity I have a TextView: textV1. I also have a method in MainActivity that updates that textview:

public void updateTheTextView(final String t) {
    MainActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            TextView textV1 = (TextView) findViewById(R.id.textV1);
            textV1.setText(t);
        }
    });
}

在一个BroadcasrReceiver我需要在MainActivity更新textV1文本。

In a BroadcasrReceiver I need to update the text in textV1 in MainActivity.

public class NotifAlarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
            // other things done here like notification

            // NEED TO UPDATE TEXTV1 IN MAINACTIVITY HERE
    }
}

如何才能做到这一点?该BroadcastReceiver的是从一个服务运行。这code我不能改变。我可以访问并在的onReceive改变MainActivity textV1()?我尝试过很多事情,但都失败了。

How can this be done? The BroadcastReceiver is run from a service. This code I cannot change. Can I access and change textV1 in MainActivity from onReceive()? I've tried many things but all fail.

推荐答案

在你的 MainActivity 初始化 MainActivity 象下面这样的类。

In your MainActivity initialize a variable of MainActivity class like below.

public class MainActivity extends Activity {
    private static MainActivity ins;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ins = this;     
    }

    public static MainActivity  getInstace(){
        return ins;
    }

    public void updateTheTextView(final String t) {
        MainActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                TextView textV1 = (TextView) findViewById(R.id.textV1);
                textV1.setText(t);
            }
        });
    }
}


public class NotifAlarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            MainActivity  .getInstace().updateTheTextView("String");
        } catch (Exception e) {

        }           
    }
}