2016-10-01 29 views
0

我有一个可以传输音频的应用程序。在一个单独的线程中,我呼叫我的服务在向用户显示进度对话框时启动。 Service将启动音频或在10秒内发生错误。我现在使用的这种奇怪的方式是,当Service确定音频已准备就绪并准备好或发生错误时,它会使用该信息将本地广播消息发送回我的Activity。这表示我的主要活动是服务已完成加载和准备媒体,我可以关闭进度对话框等。最好的方式来循环等待一个小的后台任务?

现在我有MainActivity只在do while循环中等待,显示进度对话框,检查变量直到它从变更上述变量的服务接收广播

我知道,这是可能不这样做,所以我的问题是正确的做法,什么是做到这一点的正确方法?谢谢。

+1

摆脱循环。 'ProgressDialog'应该足够了。收到广播时,请将其解除。 –

回答

0

这种忙碌的等待对于处理这种情况绝对不是一个好主意。你可能会考虑有一个像这样声明的接口。

public interface MediaResponseListener { 
    void mediaResponseReceiver(String result); 
} 

然后,你需要实现interfaceMainActivity这样。

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过,当你开始从你的ServiceMainActivity通过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); 
} 

虽然开始从ServiceActivity需要将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.