从广播接收器更新活动UI组件?

Tar*_*ney 7 java android broadcastreceiver

我有非常基本的问题.它可能很简单,但我没有得到它.我有一个Activity,我正在使用一些UI组件.我还有一个广播接收器(从清单注册) ,我需要更新Activity类的一些UI组件.喜欢 -

    Class MyActivity extends Activity
     {

        onCreate(){

         //using some UI component lets say textview
           textView.setText("Some Text");
        }

       updateLayout()
       {
         textView.setText("TextView Upadated...");
       }
 }


Class broadCastReceiver
{

    onReceive()
    {
       //here I want to update My Activity component like 
       UpdateLayout();

    }

} 
Run Code Online (Sandbox Code Playgroud)

为此 - 一个解决方案是使updateLayout()方法公共静态,并通过活动引用在接收器类中使用该方法.但我认为,这不是正确的方法.有没有正确的方法来做到这一点?

Rit*_*une 6

您可以在运行时注册和取消注册接收器,而不是在清单中注册接收器,如下所示:

还要确保在Intent Filter中使用正确的Action注册接收器.

public class MyActivity extends Activity{

// used to listen for intents which are sent after a task was
// successfully processed
private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        new UpdateUiTask().execute();
    }
};

@Override
public void onResume() {        
    registerReceiver(mUpdateReceiver, new IntentFilter(
            YOUR_INTENT_ACTION));
    super.onResume();
}

@Override
public void onPause() {     
    unregisterReceiver(mUpdateReceiver);
    super.onPause();
}


// used to update the UI
private class UpdateUiTask extends AsyncTask<Void, Void, String> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(Void... voids) {
        Context context = getApplicationContext();
        String result = "test";
        // Put the data obtained after background task. 
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO: UI update          
    }
}  

}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Dam*_*tla 4

如果您确实必须继续使用BroadcastReceiver注册的,AndroidManifest.xml那么您可以考虑使用事件总线。Square有一个很酷的开源库Otto

它很好地实现了发布者/订阅者模式。你会在网上找到很多如何使用它的例子,非常简单。首先查看奥托的网站

如果您可以直接注册/取消注册接收器,那么Activity我会遵循@Ritesh Gune 的回答。