android - PhoneGap Android Plugin - 关闭插件 Activity

标签 android cordova cordova-plugins

我已经编写了一个 PhoneGap Android 插件并在那里打开了第二个 Activity :

 cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Context context = cordova.getActivity().getApplicationContext();
            Intent intent = new Intent(context, secondActivity.class);
            cordova.getActivity().startActivity(intent);
        }
    });

现在我想用一个按钮关闭 Activity 并将插件结果发送到 JavaScript,但我无法关闭 Activity 并返回到 PhoneGap 应用程序 - 我该怎么做?

我希望有人能帮助我。感谢您的所有回答。

最佳答案

在你的插件中,使用startActivityForResult来自 CordovaInterface 类而不是 startActivity来自安卓:

this.cordova.startActivityForResult(this,intent,0);

(0是一个int值,用于标识启动的activity,如果需要启动多个activity,则使用其他数字)

在您的 Activity 中,您添加以下函数以将结果返回给插件:

public void returnResult(int code, String result) {
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", result);
    setResult(code, returnIntent);
    finish();
}

因此,当您想要退出您的 Activity 时,您可以使用 RESULT_CANCELED 或 RESULT_OK 以及表示您想要返回的内容的字符串来调用此函数。

最后在您的插件类中,添加以下函数:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch (requestCode) {
    case 0: //integer matching the integer suplied when starting the activity
         if(resultCode == android.app.Activity.RESULT_OK){
             //in case of success return the string to javascript
             String result=intent.getStringExtra("result"); 
             this.callbackContext.success(result);
         }
         else{
             //code launched in case of error
             String message=intent.getStringExtra("result");
             this.callbackContext.error(message);
         }
         break;
    default:
         break;
    }
}

希望这就是您要找的。

关于android - PhoneGap Android Plugin - 关闭插件 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21858861/

相关文章:

ios - 如何在 PhoneGap 构建中使用 SVG 图像作为启动画面?

java - 访问 CordovaWebView 对象

android - 用作 LaunchedEffect 键时出现 NetworkOnMainThreadException

java - 如何使用 Jetpack 库保存 Activity 实例

javascript - 使用 PhoneGap 时从 iframe 调用父 jQuery 函数

ios - 使用Cordova应用程序在iOS上列出附近的wifi网络

cordova - Ionic 4 - 自定义上下文菜单

android - 登录 facebook android 时授权对话框出现两次

java - 如何使用在另一个类中声明的数组

cookies - 如何清除我的phonegap应用程序中的外国cookie?