正如标题所说,我有一个启动IntentService的Activity。在IntentService完成所有工作之后,我希望它将结果广播回我的Activity。但是,当我这样做时,我的BroadcastReceiver的onReceive方法不会被调用。我正在尝试从Android文档中遵循本指南:Report Status From an IntentService
这就是所有设置的方式:
我有一个类StatusReceiver,它扩展了BroadcastReceiver:
class StatusReceiver extends BroadcastReceiver{
Context mContext;
public StatusReceiver(Context context) {
mContext = context;
}
@Override
public void onReceive(Context context, Intent intent) {
boolean success;
success = intent.getBooleanExtra("success", false);
if(success)
Toast.makeText(mContext, "Profile picture updated.", Toast.LENGTH_SHORT).show();
else
Toast.makeText(mContext, "Profile picture couldn't be updated.", Toast.LENGTH_SHORT).show();
}
}
在我的Activity的onCreate()中,我实例化一个StatusReceiver:
//This broadcast receiver will receive the result of image uploads.
statusReceiver = new StatusReceiver(getApplicationContext());
在我的onResume中,我注册了接收器:
@Override
protected void onResume() {
super.onResume();
//register the receiver
LocalBroadcastManager.getInstance(UserProfileSettings.this).registerReceiver(statusReceiver, new IntentFilter("result"));
}
在我的onPause()中,我取消注册接收器:
@Override
protected void onPause() {
super.onPause();
//unregister receiver when activity is paused
LocalBroadcastManager.getInstance(UserProfileSettings.this).unregisterReceiver(statusReceiver);
}
最后,在完成所有工作后,在我的IntentService中,我想将结果发送回Activity。从Firebase CompletionListener中调用此方法:
/**
* This method broadcasts the result of writing the user's new profile picture to Firebase.
* @param success - boolean representing whether or not the write was successful.
*/
private void sendResult(final boolean success){
Intent result = new Intent("result");
result.putExtra("success", success);
LocalBroadcastManager.getInstance(this).sendBroadcast(result);
}
听众:
mDatabase.getReference(Users.NODE_NAME).child(userId).child("avatar").setValue(imageUrl, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
//if we didn't encounter an error
if(databaseError == null)
sendResult(true);
else
sendResult(false);
}
});