Send “share intent” (ACTION_SEND) from activity to service

限于喜欢 提交于 2020-04-30 08:51:20

问题


The task is to process somehow "share" intent in already running service.

As far as ACTION_SEND is an activity action we have to pick up intent in activity and broadcast it to service.

The problem is that it's logically to implement all "share intent" processing in service and use activity only for broadcasting intent.

So the service have to receive the intent (which previously received and broadcasted by activity) so we can call getType() and get****Extra***() to it in order to know what was actually shared and process this data somehow.

The intent we received in activity has the action ACTION_SEND (or ACTION_SEND_MULTIPLE), right? So logically we can change action with calling setAction() to intent object and broadcast it to our service which is already listening to this particular action.

public class HandleShareIntentActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();     
        Intent broadcastIntent = new Intent(intent);

        // If I initialize empty intent there is no problem, 
        // I'll receive it in service            
        // Intent broadcastIntent = new Intent();

        broadcastIntent.setAction(Constants.ACTION_SHARE);
        broadcastIntent.setFlags(0);
        sendBroadcast(broadcastIntent);

        finish();
    }
    // ...
}

But that is not working, I'm not receiving this intent in service. If I don't copy intent I got and broadcast an empty one, I do receive it in my service.

What I'm doing wrong?


回答1:


First, to start a service, call startService(), not sendBroadcast(). There is no reason to have the service respond to broadcasts, and you are adding security problems to your app by doing so.

Second, you have to call startService() on an Intent that will identify your service (e.g., new Intent(this, ThisIsTheService.class)). In your case, you are taking an Intent identifying an activity, using a copy constructor to make a copy of it, changing the action string, and then trying to use that.

And, since an Intent is Parcelable, you could just add it as an extra to a service-specific Intent:

startService(new Intent(this, ThisIsTheService.class).putExtra(EXTRA_SEND, getIntent()));

and your service can pick EXTRA_SEND out in onHandleIntent() (if it is an IntentService) or onStartCommand() (if it is not). This code snippet assumes that you define EXTRA_SEND to be some string somewhere.



来源:https://stackoverflow.com/questions/27207808/send-share-intent-action-send-from-activity-to-service

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