这种忙碌的等待对于处理这种情况绝对不是一个好主意。你可能会考虑有一个像这样声明的接口。
public interface MediaResponseListener {
void mediaResponseReceiver(String result);
}
然后,你需要实现interface
在MainActivity
这样。
public class MainActivity extends Activity implements MediaResponseListener {
// Your onCreate and other function goes here
// Then you need to implement the function of your interface
@Override
public void mediaResponseReceiver(String result) {
// Do something with the result
}
}
现在你在Service
类声明interface
过,当你开始从你的Service
MainActivity
通过interface
的参考。所以你的Service
可能看起来像这样。
public AudioService extends Service {
// Declare an interface
public MediaResponseListener mMediaResponseListener;
// ... Your code
// When some error occurs or you want to send some information to the launching Activity
mMediaResponseListener.mediaResponseReceiver(result);
}
虽然开始从Service
您Activity
需要将interface
的引用传递到Service
。所以在你的MainActivity
你需要做这样的事情。
private AudioService mAudioService;
mAudioService. mMediaResponseListener = this;
startService();
这里是你如何能避免忙等待,并且可以接收来自Service
不时响应。
现在行为可以通过许多其他方式实现,就像您已经尝试过使用本地广播一样。
那么,为什么你不只是在声明的Activity
一个BroadcastReceiver
当从Service
收到任何Broadcast
将被调用。
Here's a nice implementation of how you can send and receive broadcast.
摆脱循环。 'ProgressDialog'应该足够了。收到广播时,请将其解除。 –