Handle onActivityResult on a Service

后端 未结 3 2061
野趣味
野趣味 2021-02-13 17:13

So i have a simple Question , it is Possible to Handle the Method onActivityResult() in a Service if this Activity was Started from the Same Service (Using Intent) ?

In

3条回答
  •  半阙折子戏
    2021-02-13 17:38

    Thanks for a recent downvoting, whoever it was. The previous answer I gave back in 2012 is a total nonsesnse so I decided to write a proper one.

    You can not handle Activity result in a Service, but you can pass any data retrieved from onActivityResult() to a Service.

    If your Service is already running, you can call startService() with a new Intent handling the event, like so

    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE && resultCode == RESULT_OK) {
            notifyService(data);
        }
    }
    
    private void notifyService(final Intent data) {
        final Intent intent = new Intent(this, MyService.class);
        intent.setAction(MyService.ACTION_HANDLE_DATA);
        intent.putExtra(MyService.EXTRA_DATA, data);
        startService(intent);
    }
    

    And handle action in a Service. If it is already running it will not be restarted, otherwise it will be started

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            final String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case ACTION_HANDLE_DATA:
                        handleData(intent.getParcelableExtra(EXTRA_DATA));
                        // Implement your handleData method. Remember not to confuse Intents, or even better make your own Parcelable
                        break;
                }
            }
        }
        return START_NOT_STICKY;
    }
    

提交回复
热议问题