Result Back from Broadcast Receiver

半世苍凉 提交于 2019-12-13 00:45:16

问题


I am sending a broadCast from App A to app B, app B has a BroadCastReceiver to handle intent.

Now I do some operation in onReceive in App B's BroadcastReceiver and then I want to get result back to App A, so that I can have a callback, and continue operations if result is positive.

Below some code.

inside App B:

public class TripBackupReceiver extends BroadcastReceiver {
@Override
    public void onReceive(Context arg0, Intent arg1) {
        System.out.println("broadcast Received");

        // send result back to Caller Activity
    }
}  

inside App A:

Intent intent = new Intent("a_specified_action_string");
sendBroadcast(intent);  

Can anybody have any solution for this problem, please guide me with some suggestions. Thanks!!


回答1:


Why not just (sort of) send an Intent from TripBackupReceiver that is received by App A?

Something like:

public class TripBackupReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("broadcast Received");

        // send result back to Caller Activity
        Intent replyIntent = new Intent("a_specified_action_string");
        context.sendBroadcast(replyIntent);         
    }
}

You could receive this Intent in a BroadcastReceiver defines in App A. Or alternatively use the Context.startActivity(Intent) method to start an activity in App A.

You may need to implement onNewIntent() if this makes a call to an activity that is already running.


Please use signed intents for this, in order to prevent users from hacking into your Intent API.




回答2:


I was looking for something similar. This helped me tremendously.

Basically, instead of a sendBroadcast(Intent) try using a suitable form of sendOrderedBroadcast() which allows setting a BroadcastReceiver to handle results form a Receiver. A simple example:

sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle results = getResultExtras(true);

            String trail = results.getString("breadcrumb");
            results.putString("breadcrumb", trail + "->" + "sometext");
            Log.i(TAG, "Final Result Receiver = " + results.getString("breadcrumb", "nil"));
        }
    }, null, Activity.RESULT_OK, null, null);  


来源:https://stackoverflow.com/questions/18867606/result-back-from-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!