gpt4 book ai didi

android - 我可以使用 BroadcastReceiver 的回调方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:19 25 4
gpt4 key购买 nike

学习使用 Android 中的 BroadcastReceiver 类,我编写了一个小程序来接收电池充电状态并将其写入 Activity 中的三个 TextView 字段。

但是,我将 BroadcastReceiver 作为一个单独的类,以使其更简单并与 Activity 分开。因此,我必须找到一种方法来告诉我的 Activity 类电池数据已更新,或者,这是我的解决方案,将对 TextView 字段的引用从 Activity 传递到 BroadcastReceiver 类。

有谁知道是否可以从 BroadcastReceiver 中创建一个回调方法来启动一个函数,f.ex。更新 TextView ();在 Activity 中?

这是源代码——注意有两个 java 文件: http://pastebin.com/qjCTsSuH

问候,尼尔斯。

最佳答案

对我来说很有魅力的是将接口(interface)对象简单地声明为静态的。请记住,静态会导致与它们解决的问题一样多的问题,因为静态会在实例中保留它们的值。

public class MainActivity extends AppCompatActivity implements SocketMessageReceiver.ISocketMessageReceiver {

//Declare the cb interface static in your activity
private static SocketMessageReceiver.ISocketMessageReceiver iSocketMessageReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);

//Assign this
iSocketMessageReceiver = this;
socketMessageReceiver.registerCallback(iSocketMessageReceiver);
}

@Override
public void sendSocketMessage(String socketMessage) {
lblEchoMessage.setText(socketMessage);
}

}

在你的接收器中......

public class SocketMessageReceiver extends BroadcastReceiver {

interface ISocketMessageReceiver {
void sendSocketMessage(String socketMessage);
}

//Also declare the interface in your BroadcastReceiver as static
private static ISocketMessageReceiver iSocketMessageReceiver;

@Override
public void onReceive(Context context, Intent intent) {

if(intent.getAction().equals("com.WarwickWestonWright.SocketExample.RECEIVE")) {
iSocketMessageReceiver.sendSocketMessage(intent.getBundleExtra("DATA").getString("DATA"));
}

}

public void registerCallback(ISocketMessageReceiver iSocketMessageReceiver) {
this.iSocketMessageReceiver = iSocketMessageReceiver;
}

}

关于android - 我可以使用 BroadcastReceiver 的回调方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22115843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com