从android中的另一个应用程序获取数据

时间:2014-02-21 04:25:27

标签: java android android-intent android-manifest

我安装了两个应用程序app1和app2。 我想从app1启动app2的活动。然后使用app2中的一些数据回到app1上的活动。但我能够返回app1,但无法获取数据。

来自app1的

Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, sampleText);
        intent.setType("text/plain");
        intent.setComponent(new ComponentName("com.example.app2","com.example.app2.MainActivity"));     
        startActivity(intent);
来自app2的

Intent goBack = new Intent();
        goBack.putExtra("result","asdaf");
        setResult(RESULT_OK, goBack);
        finish();

app1的清单:

<intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

app2的清单:

 <intent-filter>
                <action android:name="android.intent.action.MAIN" />                
                <category android:name="android.intent.category.LAUNCHER" />               
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />    
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />    
            </intent-filter>

我没有在app1中获得功能。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                 
          if (requestCode == 1) {

             if(resultCode == RESULT_OK){      
                 String result=data.getStringExtra("result");                   
                TextView tv = (TextView)findViewById(R.id.textView3);
                tv.setText(result);
             }
             if (resultCode == RESULT_CANCELED) {    
                 //Write your code if there's no result
             }
          }
        }

我在这里缺少什么?是否需要为此进行任何设置?

1 个答案:

答案 0 :(得分:2)

您应该在“app1”中使用startActivityForResult:

startActivityForResult(intent, SOME_CONSTANT);

您传递的常量将作为requestCode参数传回。因此,在您的情况下,您似乎希望传入1。

有关详细信息,请参阅文档:Android Developers