我需要检查服务在 Activity 中更改变量值的时间,以便我可以使用新值更新 UI。我目前正在使用无限循环在新线程中检查此问题,这会使用大量资源吗/是否有更有效的方法来执行此操作?
最佳答案
您应该使用来自服务的广播来发送变量中的更改。首先在您的主 Activity 中创建一个广播。
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Broadcast","broadcast received");
String value = intent.getStringExtra("Variable"); // this will get the value
// send from Service
}
};
接下来设置广播监听的 Intent 过滤器。您可以在 Activity 的 onCreate()
中执行此操作。
IntentFilter intentFilter = new IntentFilter("FROM_SERVICE");
registerReceiver(broadcastReceiver,intentFilter);
然后在您的服务中您必须发送一个广播。如果你想从服务发送一些数据到 Activity ,那么你必须用下面的代码替换上面的代码
Intent intent = new Intent("FROM_SERVICE");
intent.putExtra("Variable", "change");
sendBroadcast(intent);
关于java - 使用无限循环检查变量变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20937100/