无法执行任务:任务已在运行 [英] cannot execute task : the task is already running

查看:78
本文介绍了无法执行任务:任务已在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一款可以在FB上共享视频的游戏,该游戏之前运行良好,但是我不知道现在如何得到此错误.另外,我获得了所有许可,但现在没有给我任何许可. 在FB RequestAsyncTask类中,我对AlertDialog进行了一些修改,以显示上传视频的过程.

I developed a game that shares video on FB, it was working well before but I dunno how now I'm getting this error. Also I was getting all permission and now it's not giving me any. And in FB RequestAsyncTask class I made some modifications for AlertDialog that show process of uploading video.

这是我执行AsyncTask的地方

Here is where I'm executing AsyncTask

Request request = new Request(session, "me/videos", postParam, HttpMethod.POST, callback);
RequestAsyncTask reqTask = new RequestAsyncTask(Result.this, request);
reqTask.execute();

和Logcat

04-19 18:40:47.048: I/System.out(20093): no of permission it has = 0
04-19 18:40:47.963: D/AndroidRuntime(20093): Shutting down VM
04-19 18:40:47.963: W/dalvikvm(20093): threadid=1: thread exiting with uncaught exception (group=0x418cb700)
04-19 18:40:47.968: E/AndroidRuntime(20093): FATAL EXCEPTION: main
04-19 18:40:47.968: E/AndroidRuntime(20093): java.lang.IllegalStateException: Cannot execute task: the task is already running.
04-19 18:40:47.968: E/AndroidRuntime(20093):    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at android.os.AsyncTask.execute(AsyncTask.java:534)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.RequestAsyncTask.executeOnSettingsExecutor(RequestAsyncTask.java:205)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.Request.executeBatchAsync(Request.java:1094)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.RequestBatch.executeAsyncImpl(RequestBatch.java:225)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.RequestBatch.executeAsync(RequestBatch.java:204)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.AuthorizationClient.validateSameFbidAndFinish(AuthorizationClient.java:279)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.AuthorizationClient.completeAndValidate(AuthorizationClient.java:215)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.AuthorizationClient$GetTokenAuthHandler.getTokenCompleted(AuthorizationClient.java:536)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.AuthorizationClient$GetTokenAuthHandler$1.completed(AuthorizationClient.java:514)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.GetTokenClient.callback(GetTokenClient.java:121)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.GetTokenClient.handleMessage(GetTokenClient.java:107)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.GetTokenClient.access$0(GetTokenClient.java:100)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.facebook.GetTokenClient$1.handleMessage(GetTokenClient.java:43)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at android.os.Looper.loop(Looper.java:137)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at android.app.ActivityThread.main(ActivityThread.java:5295)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at java.lang.reflect.Method.invokeNative(Native Method)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at java.lang.reflect.Method.invoke(Method.java:525)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
04-19 18:40:47.968: E/AndroidRuntime(20093):    at dalvik.system.NativeStart.main(Native Method)
04-19 18:40:59.128: I/Process(20093): Sending signal. PID: 20093 SIG: 9
04-19 18:40:59.463: I/dalvikvm(20943): Turning on JNI app bug workarounds for target SDK version 10...

如果有人想看看代码的其他部分,请告诉我,我会给你的.我需要尽快对其进行调试,然后上传到Google Play

if anyone wanna look at any other part of code just let me know I'll give you. ASAP I need to debug this and upload to Google Play

编辑

这是我正在使用fb post的完整代码,将项目替换为新项目后,它可以正常工作,但是当我在FB Developer上更改应用程序名称后,它询问了正常的权限,然后又开始再次给我同样的错误./p>

here is whole code where I'm using fb post, After replace project into new one it was working but after I change application name on FB Developer it ask permission that is normal then it start to give me same error again.

package com.yceo.anlatbana;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import org.json.JSONObject;

import com.yceo.anlatbana.R;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.Session.StatusCallback;
import com.yceo.anlatbana.util.ListViewAdapter;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;


public class Result extends Activity {

    static final String APP_ID = "dont wanna show";
    Session session;
    private boolean pendingRequest;
    static final String PENDING_REQUEST_BUNDLE_KEY = "com.yceo.anlatbana:PendingRequest";
    static final List<String> PERMISSIONS = Arrays.asList("publish_actions");

    private TextView result;
    private Button re_play;
    private Button save_video;
    private Button watch_video;
    private Button share_video;
    private ImageView score_top;
    private ImageView score;

    public static int isSaved = 0;
    public static int doubleClick = 0;
    public static int sentAlready = 0;

    public static int width;
    public static int height;

    int resultPoint;

    private Typeface font_score;

    String path = VideoViewTest.videoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        height = displaymetrics.heightPixels;
        width = displaymetrics.widthPixels;

        this.session = createSession();
        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        re_play= (Button) findViewById(R.id.result_button_replay);
        save_video= (Button) findViewById(R.id.result_button_save_video);
        result = (TextView) findViewById(R.id.result_result_tw);
        watch_video= (Button) findViewById(R.id.result_button_play_video);
        share_video= (Button) findViewById(R.id.result_button_share_video);

        score_top= (ImageView) findViewById(R.id.iw_result_point_top);
        score= (ImageView) findViewById(R.id.img_score);

        font_score=Typeface.createFromAsset(getAssets(),"font/PATAGONIA.TTF");

        int trueNumber = VideoViewTest.true_answers.size();
        int falseNumber = VideoViewTest.false_answers.size();

        resultPoint = ((trueNumber*9) - (falseNumber*2));

        result.setText(String.valueOf(resultPoint));
        result.setTypeface(font_score);
        result.setTextSize(TypedValue.COMPLEX_UNIT_PX, (int)(width*0.05));


        RelativeLayout.LayoutParams lp_result_button1 = new RelativeLayout.LayoutParams(((int)(width*0.1)), ((int)(width*0.1)));
        lp_result_button1.setMargins(((int)(width*0.035)), 0, ((int)(width*0.035)), 0);
        lp_result_button1.addRule(RelativeLayout.LEFT_OF, R.id.result_button_save_video);

        RelativeLayout.LayoutParams lp_result_button2 = new RelativeLayout.LayoutParams(((int)(width*0.1)), ((int)(width*0.1)));
        lp_result_button2.setMargins(((int)(width*0.035)), 0, ((int)(width*0.035)), 0);
        lp_result_button2.addRule(RelativeLayout.LEFT_OF, R.id.result_result_tw);

        RelativeLayout.LayoutParams lp_result_button3 = new RelativeLayout.LayoutParams(((int)(width*0.1)), ((int)(width*0.1)));
        lp_result_button3.setMargins(((int)(width*0.035)), 0, ((int)(width*0.035)), 0);
        lp_result_button3.addRule(RelativeLayout.CENTER_HORIZONTAL);

        RelativeLayout.LayoutParams lp_result_button4 = new RelativeLayout.LayoutParams(((int)(width*0.1)), ((int)(width*0.1)));
        lp_result_button4.setMargins(((int)(width*0.035)), 0, ((int)(width*0.035)), 0);
        lp_result_button4.addRule(RelativeLayout.RIGHT_OF, R.id.result_result_tw);

        RelativeLayout.LayoutParams lp_result_button5 = new RelativeLayout.LayoutParams(((int)(width*0.1)), ((int)(width*0.1)));
        lp_result_button5.setMargins(((int)(width*0.035)), 0, ((int)(width*0.035)), 0);
        lp_result_button5.addRule(RelativeLayout.RIGHT_OF, R.id.result_button_play_video);

        re_play.setLayoutParams(lp_result_button1);
        save_video.setLayoutParams(lp_result_button2);
        result.setLayoutParams(lp_result_button3);
        watch_video.setLayoutParams(lp_result_button4);
        share_video.setLayoutParams(lp_result_button5);

        score_top.setLayoutParams(new LinearLayout.LayoutParams(((int)(width*0.0654545)), ((int)(width*0.0341818))));
        score.setLayoutParams(new LinearLayout.LayoutParams(((int)(width*0.1)), ((int)(width*0.1))));

        LinearLayout.LayoutParams lp_result_llw = new LinearLayout.LayoutParams(((int)(width/2)-((int)(width*0.16))), LayoutParams.WRAP_CONTENT);
        lp_result_llw.setMargins(((int)(width*0.15)), 0, ((int)(width*0.01)), 0);

        LinearLayout.LayoutParams lp_result_rlw = new LinearLayout.LayoutParams(((int)(width/2)-((int)(width*0.16))), LayoutParams.WRAP_CONTENT);
        lp_result_rlw.setMargins(((int)(width*0.01)), 0, ((int)(width*0.15)), 0);

        final ListView correct_answer_lw = (ListView) findViewById(R.id.result_correct_lw);
        final ListView wrong_answer_lw = (ListView) findViewById(R.id.result_wrong_lw);

        correct_answer_lw.setLayoutParams(lp_result_llw);
        wrong_answer_lw.setLayoutParams(lp_result_rlw);

        ListViewAdapter adapter_correct_lw = new ListViewAdapter(
                this, 
                R.layout.item_correct_answer, 
                R.id.item_correct, 
                VideoViewTest.true_answers,
                height);

        correct_answer_lw.setAdapter(adapter_correct_lw);
        adapter_correct_lw.notifyDataSetChanged();

        ListViewAdapter adapter_wrong_lw = new ListViewAdapter(
                this, 
                R.layout.item_wrong_answer, 
                R.id.item_wrong, 
                VideoViewTest.false_answers,
                height);

        wrong_answer_lw.setAdapter(adapter_wrong_lw);
        adapter_wrong_lw.notifyDataSetChanged();

        re_play.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                onBackPressed();
                VideoViewTest.true_answers.clear();
                VideoViewTest.false_answers.clear();
            }
        });

        save_video.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Video Kaydedildi", Toast.LENGTH_SHORT).show();
                isSaved = 1;
            }
        });

        watch_video.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent in = new Intent(getBaseContext(), AndroidVideoPlayer.class);
                startActivity(in);
            }
        });

        share_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                clickHandler(v);
                if (doubleClick==0 && sentAlready==0) {

                    share_it();
                    doubleClick=1;
                    sentAlready=1;
                }
                else
                    Toast.makeText(getBaseContext(), "Already shared on Facebook", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        if (VideoViewTest.videoPath != null) {
            if (isSaved == 0) {
                File file = new File(VideoViewTest.videoPath);
                if(file.exists())
                    file.delete();
                finish();
            }
        }
        finish();
        doubleClick = 0;
        sentAlready = 0;
    }

    @Override
    protected void onPause() {
        doubleClick=0;
//      Log.i("pause", "oldu");
        super.onPause();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (this.session.onActivityResult(this, requestCode, resultCode, data)
                && pendingRequest && this.session.getState().isOpened()) {
            share_it();
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        pendingRequest = savedInstanceState.getBoolean(
                PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }

    @Override
    protected void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private Session createSession() {
        Session session = Session.getActiveSession();
        if (session == null || session.getState().isClosed()) {
            session = new Session.Builder(getApplicationContext()).setApplicationId(APP_ID).build();
            Session.setActiveSession(session);
        }
        return session;
    }

    public void clickHandler(View v) {
        if (!session.isOpened()) {
            StatusCallback callback = new StatusCallback() {

                @Override
                public void call(Session session, SessionState state, Exception exception) {
                    // TODO Auto-generated method stub
                    if (exception != null) {
                        Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_SHORT).show();
                        Result.this.session = createSession();
                    }
                }
            };

            pendingRequest = true;
            this.session.openForRead(new Session.OpenRequest(this).setCallback(callback));
        }
    }

    public void share_it() {
        if (session.isOpened()) {
            if (session != null) {
                List<String> permission = session.getPermissions();
                System.out.println("no of permission it has = " + permission.size());
                for (int i = 0; i < permission.size(); i++) {
                    System.out.println("Permission " + i + " => " + permission.get(i));
                }
                if (permission.size() == 0) {
                    pendingRequest = true;
                    Session.NewPermissionsRequest publishPermission = new Session.NewPermissionsRequest(this, PERMISSIONS);
                    session.requestNewPublishPermissions(publishPermission);
                } 
                else {

                    final Bundle postParam = new Bundle();
                    String dataMsg = "AnlatBana Game Video";

                    byte[] data = null;
//                  InputStream is = null;

                    File file=new File(path);


/*                  try {
                        is = new FileInputStream(path);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
*/                  try {
//                      data = readBytes(is);
                        data = getBytesFromFile(file);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

/*                  Bitmap bi = BitmapFactory.decodeFile(path);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    data = baos.toByteArray();

                    postParam.putByteArray("picture", data);
*/              

                    postParam.putString("message", dataMsg);
                    postParam.putString("description", scoreDescription());
//                  postParam.putString("title", "title");
                    postParam.putString("contentType", "video/quicktime");
                    postParam.putByteArray("video.mov", data);

                    final Request.Callback callback = new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            // TODO Auto-generated method stub
                            String postId = null;

                            try {
                                JSONObject graphObject = response.getGraphObject().getInnerJSONObject();
                                postId = graphObject.getString("id");

                            } catch (Exception ex) {
                                System.out.println("Error Occured fetching grapho objecyt " + ex.getMessage());
                            }
                        }
                    };

                    Request request = new Request(Session.getActiveSession(), "me/videos", postParam, HttpMethod.POST, callback);
                    RequestAsyncTask reqTask = new RequestAsyncTask(Result.this, request);
                    reqTask.execute();


/*              Request request = new Request(session, "me/photos", postParam, HttpMethod.POST, callback);
                RequestAsyncTask reqTask = new RequestAsyncTask(request);
                reqTask.execute();
*/
                }
            }
        }
    }

/*  public byte[] readBytes(InputStream inputStream) throws IOException {
        // This dynamically extends to take the bytes you read.
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        // This is storage overwritten on each iteration with bytes.
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // We need to know how may bytes were read to write them to the byteBuffer.
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }

        // And then we can return your byte array.
        return byteBuffer.toByteArray();
    }
*/  
    @SuppressWarnings("resource")
    public static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length) && ((numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)) {
            offset += numRead;
/*          progressBar.setProgress((int) ((offset / (float) length) * 100));
            Log.i("asd", String.valueOf(progressBar.getProgress()));
*/      }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file);
        }

        is.close();
        return bytes;
    }

    public String scoreDescription() {
        String message = null;

        if (resultPoint < 0) {
            message = String.valueOf(resultPoint) + " Puan" + " - Yok artık!!!";
        }
        if (0 <= resultPoint && resultPoint < 10) {
            message = String.valueOf(resultPoint) + " Puan" + " - Daha çok çalışman lazım";
        }
        if (10 <= resultPoint && resultPoint < 20) {
            message = String.valueOf(resultPoint) + " Puan" + " - Fena değil";
        }
        if (20 <= resultPoint && resultPoint < 25) {
            message = String.valueOf(resultPoint) + " Puan" + " - Güzel skor";
        }
        if (25 <= resultPoint) {
            message = String.valueOf(resultPoint) + " Puan" + " - Çok hızlısın";
        }

        return message;

    }

}

推荐答案

AsyncTask只能执行一次.您在代码中的其他地方调用执行吗?

An AsyncTask can only be executed once. Are you calling execute somewhere else in your code?

这篇关于无法执行任务:任务已在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆