安卓的BroadcastReceiver的onReceive更新的TextView在MainActivity [英] Android BroadcastReceiver onReceive Update TextView in MainActivity

查看:1213
本文介绍了安卓的BroadcastReceiver的onReceive更新的TextView在MainActivity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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) {

        }           
    }
}

这篇关于安卓的BroadcastReceiver的onReceive更新的TextView在MainActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆