Android BroadcastReceiver onReceive Update TextView in MainActivity(Android BroadcastReceiver onReceive 更新MainActivity中的TextView)
问题描述
在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!