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()方法公共静态,并通过活动引用在接收器类中使用该方法.但我认为,这不是正确的方法.有没有正确的方法来做到这一点?
您可以在运行时注册和取消注册接收器,而不是在清单中注册接收器,如下所示:
还要确保在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)
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
3893 次 |
| 最近记录: |