java – Android BroadcastReceiver onReceive更新MainActivity中的TextView

前端之家收集整理的这篇文章主要介绍了java – Android BroadcastReceiver onReceive更新MainActivity中的TextView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在MainActivity中,我有一个TextView:textV1.我还在MainActivity中有一个方法来更新该文本视图:
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中的文本.

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是从服务运行的.这段代码我不能改变.可以从onReceive()访问和更改MainActivity中的textV1吗?我尝试了许多事情,但都失败了.

解决方法

在MainActivity中,如下所示,初始化MainActivity类的变量.
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) {

        }           
    }
}
原文链接:https://www.f2er.com/java/122750.html

猜你在找的Java相关文章