无法执行任务:任务已在运行

时间:2014-04-19 15:43:14

标签: android facebook android-asynctask

我开发了一款在FB上分享视频的游戏,之前运行良好,但我不知道现在我是如何得到这个错误的。我也获得了所有的许可,现在它没有给我任何许可。 在FB RequestAsyncTask类中,我对AlertDialog做了一些修改,显示了上传视频的过程。

这是我执行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

修改

这里是整个代码,我使用fb post,将项目更换为新的后它正在工作但是我在FB Developer上更改应用程序名称之后它会问正常的权限然后再开始给我同样的错误

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;

    }

}

4 个答案:

答案 0 :(得分:11)

AsyncTask只能执行一次。你在代码中的其他地方调用执行程序吗?

答案 1 :(得分:9)

类AsyncTask的实例只能执行一次。因此,每次调用execute()时都必须创建新实例。

new ClassName().execute();

答案 2 :(得分:2)

您可以通过新的CLASS_NAME()多次使用AsyncTask。执行() CLASS_NAME扩展了AsyncTask,没有来自CLASS_NAME的创建实例

答案 3 :(得分:-1)

只需在异步任务线程池

中执行Async任务即可
new RequestAsyncTask(Result.this, 
      new Request(session, "me/videos", postParam, HttpMethod.POST, callback))
                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);