簡體   English   中英

aSync任務無法執行兩次

[英]aSync Task can't be executed twice

我正在開發需要將文件上傳到服務器的應用程序。 但要上傳需要登錄(工作)的文件然后獲取網址(工作)然后上傳(強制關閉)

logcat:

10-13 14:10:27.494: E/AndroidRuntime(26578): FATAL EXCEPTION: main
10-13 14:10:27.494: E/AndroidRuntime(26578): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:578)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.os.AsyncTask.execute(AsyncTask.java:534)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.spxc.bayfiles.FilesActivity.onOptionsItemSelected(FilesActivity.java:294)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.actionbarsherlock.app.SherlockActivity.onMenuItemSelected(SherlockActivity.java:208)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchOptionsItemSelected(ActionBarSherlockNative.java:93)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.actionbarsherlock.app.SherlockActivity.onOptionsItemSelected(SherlockActivity.java:159)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.app.Activity.onMenuItemSelected(Activity.java:2566)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:986)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:547)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:115)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.view.View.performClick(View.java:4240)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.view.View$PerformClick.run(View.java:17721)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.os.Handler.handleCallback(Handler.java:730)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.os.Looper.loop(Looper.java:137)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at android.app.ActivityThread.main(ActivityThread.java:5103)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at java.lang.reflect.Method.invokeNative(Native Method)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at java.lang.reflect.Method.invoke(Method.java:525)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:112)
10-13 14:10:27.494: E/AndroidRuntime(26578):    at dalvik.system.NativeStart.main(Native Method)

我的代碼:(handleJsonObject):

private void handleJsonObject(JSONObject object) {

        try {
            sUpload = object.getString("uploadUrl");            
            HttpClient httpclient = new DefaultHttpClient();

            //post request to send the video 

            File sdCardRoot = Environment.getExternalStorageDirectory();
            File myDir = new File(sdCardRoot, "Download");

            HttpPost httppost = new HttpPost(sUpload);
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy( policy);
            FileBody video_file1 = new FileBody(new File(myDir + "/test.txt"));
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("file=", video_file1);                    
            httppost.setEntity(reqEntity);

            // DEBUG
            System.out.println( "executing request " + httppost.getRequestLine( ) );
            HttpResponse response = null;
            try {
                response = httpclient.execute( httppost );
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            HttpEntity resEntity = response.getEntity( );

            // DEBUG
            System.out.println( response.getStatusLine( ) );
            if (resEntity != null) {
              try {
                System.out.println( EntityUtils.toString( resEntity ) );
            } catch (org.apache.http.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            } // end if
            if (resEntity != null) {
              try {
                resEntity.consumeContent( );
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            } // end if

            httpclient.getConnectionManager( ).shutdown( );


        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data: " + e.toString());
            Crouton.makeText(this, "Something went wrong!", Style.ALERT).show();
        }
    }

代碼(aSync)調用后置代碼(handleJsonObject):

asyncTask.setJsonListener(new JsonListener() {
                public void onObjectReturn(JSONObject object) {
                    handleJsonObject(object);
                }
            });
            asyncTask.execute("http://api.bayfiles.net/v1/file/uploadUrl?session=" + sessionId);

我無法弄清楚為什么代碼不起作用? 任何幫助深表感謝!

正如異常本身所解釋的那樣,除非您創建一個new實例並調用.execute ,否則不能多次執行AsyncTask

例如:

async = new AsyncTask();
async.execute();

*為了執行多次,您需要重新創建實例(使用new執行它的次數。

我使用這個代碼,它適用於我:

    if ((eliminar_op_async != null) && eliminar_op_async.getStatus() == AsyncTask.Status.RUNNING) {
        if (eliminar_op_async.isCancelled()) {
            eliminar_op_async = new EliminarOperacion();

            eliminar_op_async.execute(id_operacion,posicion_operacion);
        }
        else {
            // Nada
        }
    }

    if ((eliminar_op_async != null) && eliminar_op_async.getStatus() == AsyncTask.Status.PENDING) {
        eliminar_op_async.execute(id_operacion,posicion_operacion);
    }

    if ((eliminar_op_async != null) && eliminar_op_async.getStatus() == AsyncTask.Status.FINISHED) {
        eliminar_op_async = new EliminarOperacion();

        eliminar_op_async.execute(id_operacion,posicion_operacion);
    }

    if (eliminar_op_async == null) {
        eliminar_op_async = new EliminarOperacion();

        eliminar_op_async.execute(id_operacion,posicion_operacion);
    }

您可以通過使用async.cancel(true)調用async實例來取消,這樣就可以確保只有一個async實例

您不能多次執行AsyncTask,因此要修復此錯誤,只需將其包裝在如下條件中:async = new AsyncTask();

                 if (async==null){

                   async.execute();

                    }

當您嘗試在viewpager中運行Asynctask時,通常會發生此錯誤。 當您在片段中運行asynctask並滑動到下一個片段時,返回到上一個片段會觸發重新執行該片段中的asynctask,從而導致應用程序崩潰。 因此,您必須通過將asynctask包裝在條件中來檢查是否已經執行了asynctask。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM