Handle onActivityResult on a Service

后端 未结 3 1977
野趣味
野趣味 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:49

    Open Transparent activity from service and use BroadcastReceiver in service. Follow the steps in detail.

    1. Open transparent activity from Service

    Intent i = new Intent(mContext, FloatingServiceSupportActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.putExtra("action", "SpeechRegnition");
    mContext.startActivity(i);
    

    // For transparent activity use this code in AndroidManifest.xml

    
    

    2. Create BroadcastReceiver in Service

    BroadcastReceiver brOnActivityResult = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO:
        }
    };
    

    3. Register this broadcast in onCreate of Service

    IntentFilter brintent = new IntentFilter();
    brintent.addAction("brActionFloatingServiceOnActivityResult");
    mContext.registerReceiver(brOnActivityResult, brintent);
    

    4. Unregister this broadcast in onDestroy of Service

    mContext.unregisterReceiver(brOnActivityResult);
    

    5. Do work in Activity by using startActivityForResult and Send broadcast from Activity's (FloatingServiceSupportActivity) onActivityResult

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    
    Intent i = new Intent();
    i.setAction("brActionFloatingServiceOnActivityResult");
    i.putExtra("action", "initTextToSpeech");
    mActivity.sendBroadcast(i);
    
    mActivity.finish();
    }
    

提交回复
热议问题