startActivityForResult在AsyncTask中不被识别为函数

时间:2014-10-10 11:19:19

标签: android cordova android-asynctask

我正在制作一个phonegap项目。我在android中为它制作了一个原生插件。在其中,AsyncTask也被调用。在其中,我有context.startActivity(intent)功能。我希望在此活动完成后执行任务。我找到了一个使用context.startActivityForResult(intent,i)的解决方案。但是这个功能无法识别。

然后我试过了,

((Activity) context).startActivityForResult(intent,1);

按照

StartActivityForResult not working in AsyncTask

但是在startActivityForResult时,我遇到了文件安装错误。

我的代码如下 -

 public class MyPlugin extends CordovaPlugin
    {
        Context context;
        CallbackContext callback;
        @Override
        public void initialize(CordovaInterface cordova, CordovaWebView webView) 
        {
            super.initialize(cordova, webView);    
        }
        @Override
        public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException 
        {   
                context=this.cordova.getActivity().getApplicationContext();
                callback=callbackContext;

                if (action.equals("plugin1"))
                { 
                     System.out.println("Inside plugin1");
                     String myurl = args.getString(0);
                     if(haveNetworkConnection()==true)
                     {
                         System.out.println("Network connected");
                         new DownloadManager().execute(myurl);
                         return true;
                     }
                     else
                     {
                         System.out.println("Network not connected");
                         callbackContext.error("Internet connection is not available.");
                         return false;
                     }
                }

                callbackContext.error("Some error has occured.Please try later.");
                return false;

        }

        public class DownloadManager extends AsyncTask<String, String, String> 
        {
            @Override
            public String doInBackground(String... arg0)
            {
                try
                {
                    //Knowing imei number
                    TelephonyManager mngr = (TelephonyManager)context.getSystemService(context.TELEPHONY_SERVICE); 
                    String imei_device=mngr.getDeviceId();
                    //downloading and installing app
                    downloadapk(arg0[0]);
                    installapk();
                    PluginResult result = new PluginResult(PluginResult.Status.OK, "success");
                    result.setKeepCallback(true);
                    callback.success("Operation completed!!");
                    return null;
                }
                catch(Exception e)
                {
                    callback.error("Some problem occured.Try again later");
                    return null;
                }   
            }
         }
        public void installapk()
        {
             try
             { 
                Intent intent=new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(
                Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/"+fileName)),"application/vnd.android.package-archive");
                ((Activity) context).startActivityForResult(intent,1);
             }
             catch (Exception e) 
             {
                Log.e("File installing Error", e.getMessage());
                System.out.println(e.getMessage());
                callback.error("Installation Failed.Please try later");
             }
         }
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {

              if (requestCode == 1) //check if the request code is the one you've sent
              {
                     if (resultCode == Activity.RESULT_OK) 
                     {
                        System.out.println("Result is OK");
                      }
                     else
                     {
                         System.out.println("Result is not OK");    
                      }
              }


            super.onActivityResult(requestCode, resultCode, data);

        }

提前完成。

2 个答案:

答案 0 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

public class MyPlugin extends CordovaPlugin {
    Context context;
    CallbackContext callback;

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        context = this.cordova.getActivity().getApplicationContext();
        callback = callbackContext;

        if (action.equals("plugin1")) {
            System.out.println("Inside plugin1");
            String myurl = args.getString(0);
            if (haveNetworkConnection() == true) {
                System.out.println("Network connected");
                new DownloadManager().execute(myurl);
                return true;
            } else {
                System.out.println("Network not connected");
                callbackContext.error("Internet connection is not available.");
                return false;
            }
        }

        callbackContext.error("Some error has occured.Please try later.");
        return false;

    }

    public class DownloadManager extends AsyncTask<String, String, String> {
        @Override
        public String doInBackground(String... arg0) {
            try {
                //Knowing imei number
                TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
                String imei_device = mngr.getDeviceId();
                //downloading and installing app
                downloadapk(arg0[0]);
                PluginResult result = new PluginResult(PluginResult.Status.OK, "success");
                result.setKeepCallback(true);
                callback.success("Operation completed!!");
                return null;
            } catch (Exception e) {
                callback.error("Some problem occured.Try again later");
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            installapk();
        }
    }

    public void installapk() {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + fileName)), "application/vnd.android.package-archive");
            ((Activity) context).startActivityForResult(intent, 1);
        } catch (Exception e) {
            Log.e("File installing Error", e.getMessage());
            System.out.println(e.getMessage());
            callback.error("Installation Failed.Please try later");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) //check if the request code is the one you've sent
        {
            if (resultCode == Activity.RESULT_OK) {
                System.out.println("Result is OK");
            } else {
                System.out.println("Result is not OK");
            }
        }


        super.onActivityResult(requestCode, resultCode, data);

    }
}

答案 1 :(得分:0)

错误是ClassCastException

如果是这样,那是因为您要使用应用程序上下文替换ActivityContext),该应用程序上下文也是Context但不是Activity ,因此无法获得startActivityForResult方法。

如果你替换它是否有效:

context = this.cordova.getActivity().getApplicationContext();

with:

context = this.cordova.getActivity();

Here是关于不同类型的上下文以及何时使用每个上下文的解释。