Android BroadcastReceiver onReceive 在 MainActivity 中更新 TextView

编程入门 行业动态 更新时间:2024-10-11 07:31:10
本文介绍了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

本文发布于:2023-11-27 09:42:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637556.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:BroadcastReceiver   Android   onReceive   TextView   MainActivity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!