android - 在不更改 Activity 类的情况下将回调传递给 startActivityForResult

标签 android android-intent android-activity

我的问题是我需要从我的站点获取 cookie。为了解决这个问题,我有一个像 http://example.com/cookie 这样的 API 端点,它使用应用架构 myapp://cookie=some_cookie

进行重定向
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (goToBrowser) { // Going to url which redirects back to this activity
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivityForResult(intent, RESULT_OK);
    } else { // Parcing incoming url
        setResult(RESULT_OK);
        finish();
    }
}

我有一个处理应用架构的 Activity。如果我无法更改 appActivity 类,我如何获取 some_cookie

更新: 我设法使用答案获取 cookie,但是当我调用 finish() 时,它返回到浏览器,而不是 Activity ,它称为浏览器

更新 2: 我更新了代码,添加了标志,但行为是一样的

最佳答案

您可以使用嗅探器 Activity :

1: 从 AndroidManifest.xml 的当前处理 Activity 中注销现有 Activity 的 Intent 过滤器(删除 Intent 过滤器数据/方案/主机/路径)

2:您可以创建一个新的 CookieSnifferActivity 并使用完全相同的外部 Intent 过滤器(您从现有 Activity 中删除的数据)将其注册到 AndroidManifest.xml 中,例如:

<activity android:name=".my.package.CookieSnifferActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http" />
        <data android:host="example.com" />
        <data android:pathPrefix="cookie"/>
    </intent-filter>
</activity>

3:在您新的 CookieSnifferActivity 的 onCreate 中,您现在应该能够读取 cookie 数据:

    getIntent().getData().getPath()

4:在CookieSnifferActivity的onActivityResult()中,转发输出结果:

protected void onActivityResult (int requestCode, int resultCode, Intent data){
    setResult(resultCode)
    finish();
    //...
}

5:最后你只想将嗅探到的 Intent 转发给之前处理的 Activity :

Intent forwarded = new Intent(getIntent());
forwarded.setClass(getPackageName(), "example.package.PreviousProcessingActivity");
startActivityForResult(forwarded, 0);

关于android - 在不更改 Activity 类的情况下将回调传递给 startActivityForResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36694766/

相关文章:

android - 将 CheckedTextViews 的 ListView 与过滤器一起使用

android - android JobScheduler 可以替代 RxJava 吗?

Android Intents,如何传递和接收 InetAddress?

android - RecyclerView 为空时的背景图片

Android 只允许调用 Activity 到预定义的 Activity/包

android - import org.w3c.dom.Document 与 android 中的另一个 import 语句冲突

Android以编程方式创建选择器

android - 打开新帖子作为意向 - Facebook 移动版

java - 在 AsyncTask 中找不到ViewById

java - 执行停止但未恢复的 Activity ?