在 MainActivity 我有一个 TextView:textV1.我在 MainActivity 中还有一个方法可以更新该文本视图:
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 从服务运行.此代码我无法更改.我可以从 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) { } } }更多推荐
Android BroadcastReceiver onReceive 在 MainActivity 中更新 TextView
发布评论