How to send data between one application to other application in android?

前端 未结 6 1095
再見小時候
再見小時候 2020-12-11 18:00

i\'ve tried to sending data between App1 to App2 via Intent in Android

i used this code but i couldn\'t resolve my problem.

<
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 18:18

    My requirement was to send the "user id" from App1 to App2 and get "username" back to App1.

    I needed to launch my app directly without any chooser. I was able to achieve this using implicit intent and startActivityForResult.

    App1 > MainActivity.java

    private void launchOtherApp() {
        Intent sendIntent = new Intent();
        //Need to register your intent filter in App2 in manifest file with same action.
        sendIntent.setAction("com.example.sender.login"); // 
        Bundle bundle = new Bundle();
        bundle.putString("user_id", "1111");
        sendIntent.putExtra("data", bundle);
        sendIntent.setType("text/plain");
        if (sendIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(sendIntent, REQUEST_CODE);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle bundle = data.getBundleExtra("data");
                String username = bundle.getString("user_name");
                result.success(username);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    

    I had two activity in App2 ie. MainActivity and LoginActivity.

    App2 > AndroidManifest.xml

    
        
            
            
            
            
        
    
    

    Sorry for this I had a little mix up with Java and Kotlin. My second app was in Kotlin, not that it will effect in any way.

    App2 > LoginActivity.java

    override fun onResume() {
        super.onResume()
        var userId = "No data received"
        val intent = intent
        if (intent != null
            && intent.action != null
            && intent.action.equals("com.example.sender.login")
        ) {
            val bundle = intent.getBundleExtra("data")
            if (bundle != null) {
                userId = bundle.getString("user_id")
                userId = " User id is $userId"
            }
        }
        tvMessage.text = "Data Received: $userId"
    }
    
    fun onClickBack(view: View) {
        val intent = intent
        val bundle = Bundle()
        bundle.putString("sesion_id", "2222")
        intent.putExtra("data", bundle)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }
    

提交回复
热议问题