예제 #1
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /*
     * Retrieve existing access_token
     */
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) facebook.setAccessExpires(expires);
    /*
     * Only call authorize when access_token is expired
     */
    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {"user_actions.music"},
          new DialogListener() {

            public void onComplete(Bundle values) {
              AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);

              // post information about the currently logged in user
              mAsyncRunner.request("me/", new meRequestListener());

              // get information about the currently played song
              mAsyncRunner.request("me/music.listens", new idRequestListener());

              // post song info to server
              mAsyncRunner.request("10150639755555154", new musicRequestListener());
            }

            public void onFacebookError(FacebookError error) {}

            public void onError(DialogError e) {}

            public void onCancel() {}
          });
    }

    if (facebook.isSessionValid()) {
      AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
      // post information about the currently logged in user
      mAsyncRunner.request("me/", new meRequestListener());

      // get information about the currently played song
      mAsyncRunner.request("me/music.listens", new idRequestListener());

      // post song info to server
      mAsyncRunner.request("10150106679409734", new musicRequestListener());

      //			// post checkin data if gps location doesn't work
      //			mAsyncRunner.request("me/friends", new checkinsRequestListener());
    }
  }
  public void facebookLoginShare(View view) {
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
      Log.d("FB Sessions", "" + facebook.isSessionValid());
      postToWall();

      // logout.setVisibility(View.VISIBLE);

      // share.setVisibility(View.GONE);

    }

    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {"email", "publish_stream"},
          new DialogListener() {

            @Override
            public void onCancel() {
              // Function to handle cancel event
            }

            @Override
            public void onComplete(Bundle values) {
              // Function to handle complete event
              // Edit Preferences and update facebook acess_token
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
            }

            @Override
            public void onError(DialogError error) {
              // Function to handle error

            }

            @Override
            public void onFacebookError(FacebookError fberror) {
              // Function to handle Facebook errors

            }
          });
    }
  }
예제 #3
0
  public static void runAfterFacebookAuthentication(
      final Activity activity,
      final Runnable runOnSuccessAuthentication,
      final Runnable runOnCancelAuthentication) {
    Facebook facebook = FacebookProvider.getFacebook();
    if (facebook.isSessionValid()) {
      runOnSuccessAuthentication.run();
    } else {
      YesNoDialogFragment dialogFragment =
          YesNoDialogFragment.newInstance(
              R.string.share_facbook_authorisation_question,
              new YesNoButtonPressedHandler() {
                @Override
                public void yesButtonPressed(DialogInterface dialog) {
                  AuthListener listener =
                      new SelfRemovingWithDelayAuthListener(runOnSuccessAuthentication);
                  FacebookSessionEvents.addAuthListener(listener);
                  FacebookUtils.loginRequest(activity, MainActivity.AUTHORIZE_ACTIVITY_RESULT_CODE);
                }

                @Override
                public void noButtonPressed(DialogInterface dialog) {
                  if (runOnCancelAuthentication != null) {
                    runOnCancelAuthentication.run();
                  }
                }
              });
      dialogFragment.show(activity);
    }
  }
예제 #4
0
  public JSONObject getResponse() {
    String response =
        "{"
            + "    \"status\": \""
            + (facebook.isSessionValid() ? "connected" : "unknown")
            + "\","
            + "    \"session\": {"
            + "        \"access_token\": \""
            + facebook.getAccessToken()
            + "\","
            + "        \"expires\": \""
            + facebook.getAccessExpires()
            + "\","
            + "        \"secret\": \"9e6c510c087d9367cf0f52034acf5954\","
            + "        \"session_key\": true,"
            + "        \"sig\": \"...\","
            + "        \"uid\": \""
            + this.userId
            + "\""
            + "    }"
            + "}";

    try {
      return new JSONObject(response);
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return new JSONObject();
  }
예제 #5
0
 /*
  * Restore the access token and the expiry date from the shared preferences.
  */
 public static boolean restore(Facebook session, Context context) {
   SharedPreferences savedSession = Preferences.getSharedPreferences(KEY);
   session.setTokenFromCache(
       savedSession.getString(TOKEN, null),
       savedSession.getLong(EXPIRES, 0),
       savedSession.getLong(LAST_UPDATE, 0));
   return session.isSessionValid();
 }
예제 #6
0
 /**
  * Request the logout for the current facebook session
  *
  * @param activity
  */
 public static void logoutRequest(Activity activity) {
   Facebook mFb = FacebookProvider.getFacebook();
   if (mFb.isSessionValid()) {
     FacebookSessionEvents.onLogoutBegin();
     AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
     asyncRunner.logout(activity, new LogoutRequestListener(activity));
   }
 }
예제 #7
0
 /**
  * Extend the facebook access token if needed
  *
  * @param context
  */
 public static void extendAceessTokenIfNeeded(Context context) {
   Facebook facebook = FacebookProvider.getFacebook();
   if (facebook != null) {
     if (facebook.isSessionValid()) {
       facebook.extendAccessTokenIfNeeded(context, null);
     }
   }
 }
예제 #8
0
 /**
  * Request the facebook authentication
  *
  * @param activity
  * @param activityCode the result code which will be handled on the onActivityResult method
  */
 public static void loginRequest(Activity activity, int activityCode) {
   Facebook mFb = FacebookProvider.getFacebook();
   if (!mFb.isSessionValid()) {
     mFb.authorize(
         activity,
         activity.getResources().getStringArray(R.array.share_facebook_permissions),
         activityCode,
         new LoginDialogListener(activity.getApplicationContext()));
   }
 }
예제 #9
0
  /*
   * Restore the access token and the expiry date from the shared preferences.
   */
  public static boolean restore(Facebook session, Context context) {
    SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    session.setAccessToken(savedSession.getString(TOKEN, null));
    session.setAccessExpires(savedSession.getLong(EXPIRES, 0));

    times = savedSession.getLong(USAGE, 0);
    maxtimes = savedSession.getLong(MAXTIMES, INITMAX);

    return session.isSessionValid();
  }
  public void updateStatusOnClick(View v) {
    /*
     * Get existing access_token if any
     */
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    /*
     * Only call authorize if the access_token has expired.
     */
    if (!facebook.isSessionValid()) {

      facebook.authorize(
          this,
          new String[] {"publish_stream", "publish_actions"},
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
              sendRequests();
            }

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
          });
    } else {
      sendRequests();
    }

    // EditText statusEditText = (EditText)
    // findViewById(R.id.statusEditText);
    // String status = statusEditText.getText().toString();

  }
예제 #11
0
  public void share(
      final Context context,
      final String link,
      final String thumb,
      final String name,
      final String description) {

    if (facebook == null) facebook = new Facebook(appID);
    final SharedPreferences mPrefs = ((Activity) context).getPreferences(context.MODE_PRIVATE);
    String access_token = mPrefs.getString(FB_ACCESS_TOKEN, null);
    long expires = mPrefs.getLong(FB_ACCESS_EXPIRY, 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {

      facebook.authorize(
          (Activity) context,
          new String[] {},
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString(FB_ACCESS_TOKEN, facebook.getAccessToken());
              editor.putLong(FB_ACCESS_EXPIRY, facebook.getAccessExpires());
              editor.commit();
              doShare(context, link, thumb, name, description);
            }

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
          });
    } else {
      doShare(context, link, thumb, name, description);
    }
  }
예제 #12
0
  public void chamarFacebook() {
    // Carrega a accessToken pra saber se o usuário
    // já se autenticou.
    loadAccessToken();

    if (!facebook.isSessionValid()) {

      facebook.authorize(
          this,
          PERMISSIONS,
          new LoginDialogListener() {

            @Override
            public void onComplete(Bundle values) {
              // TODO Auto-generated method stub
              saveAccessToken();
              // getProfileInformation();
            }

            @Override
            public void onFacebookError(FacebookError e) {
              // TODO Auto-generated method stub

            }

            @Override
            public void onError(DialogError e) {
              // TODO Auto-generated method stub

            }

            @Override
            public void onCancel() {
              // TODO Auto-generated method stub

            }
          });
    }
  }
예제 #13
0
  private void loginToFacebook() {
    String access_token = gigPrefs.getString("access_token", null);
    long expires = gigPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {
            "publish_checkins", "publish_stream",
          },
          new DialogListener() {
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = gigPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
            }

            public void onFacebookError(FacebookError error) {
              Log.i(GigFacebookLogin.class.getName() + " Error", error.toString());
            }

            public void onError(DialogError e) {
              Log.i(GigFacebookLogin.class.getName() + " Error", e.toString());
            }

            public void onCancel() {
              Log.i(GigFacebookLogin.class.getName() + " Cancel", "canceled...");
            }
          });
    }
  }
예제 #14
0
  public void loginToFacebook() {
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }
    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {"email", "publish_stream"},
          new DialogListener() {
            @Override
            public void onCancel() {}

            @Override
            public void onComplete(Bundle values) {
              // get Profile INFO
              getProfileInformation();
              // GraphUser user = null ;
            }

            @Override
            public void onError(DialogError error) {
              // Function to handle error
            }

            @Override
            public void onFacebookError(FacebookError fberror) {
              // Function to handle Facebook errors
            }
          });
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    // locks the screen in portrait mode
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.downloader);
    mtext = (TextView) findViewById(R.id.mtext);
    progress_text = (TextView) findViewById(R.id.progress_text);
    progress_download = (ProgressBar) findViewById(R.id.progress_download);
    // resume capability

    paused = false;
    resume_pause = (Button) findViewById(R.id.resume);

    // Create and launch the download thread
    downloadThread = new DownloadThread(this);
    downloadThread.start();

    // Create the Handler. It will implicitly bind to the Looper
    // that is internally created for this thread (since it is the UI thread)
    handler = new Handler();

    resume_pause.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            if (!paused) {
              paused = true;
              resume_pause.setText("Resume");
              // writeProgress(completed_downloads,total_files_to_download);
              downloadThread.requestStop();
              downloadThread = null;

            } else {
              resume_pause.setText("Pause");
              paused = false;

              initial_value = readProgress()[0];
              final_value = links.size();

              for (int i = initial_value; i < links.size(); i++) {
                downloadThread = new DownloadThread(download_photos.this);
                downloadThread.start();
                downloadThread.enqueueDownload(
                    new DownloadTask(
                        links.get(i), path, i + 1, links.size(), download_photos.this));
              }
            }
          }
        });

    // load preferences for this activity
    mPrefs = getSharedPreferences("COMMON", MODE_PRIVATE);

    // This declaration is solely meant for reading the checkbox preference for downloading high res
    // pics.
    SharedPreferences dl_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // The global variable is set after reading the  checkbox preference.
    dl_high_res_pics = dl_prefs.getBoolean("download_high_res", false);

    // load fb access token and its expiry values
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    // get friend_name and album_name from the intent which started this activity
    Intent starting_intent = getIntent();
    album_id = starting_intent.getStringExtra("id");
    album_name = starting_intent.getStringExtra("name");
    friend_name = starting_intent.getStringExtra("friend_name");

    // real album and friend name may contain characters not suitable for file names.
    // regex pattern includes most of the invalid characters in file names
    legal_album_name = album_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", "");
    legal_friend_name = friend_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", "");

    // initialise the directory structure for download
    path =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                + "/"
                + getText(R.string.app_name)
                + "/"
                + legal_friend_name
                + "/"
                + legal_album_name);
    if (dl_high_res_pics)
      path = new File(path.toString() + "/" + getText(R.string.folder_name_high_res));

    resume_file = new File(path, "resume.txt");
    // implements actions to done after receiving json object
    class meRequestListener extends BaseRequestListener {
      @Override
      public void onComplete(String response, Object state) {
        try {
          Log.i(TAG, response);
          json = Util.parseJson(response);

          // photos are in the form of a json array
          child = json.getJSONArray("data");

          int total = child.length();

          // contains links to photos
          links = new ArrayList<String>(total);

          // adds link to each photo to our list after replacing the "https" from url
          // DownloadManager does not support https in gingerbread
          for (int i = 0; i < total; i++) {
            photo_json = child.getJSONObject(i);

            if (dl_high_res_pics) {
              JSONArray image_set = photo_json.getJSONArray("images");

              // highest resolution picture has the index zero in the images jsonarray
              JSONObject highest_res_pic = image_set.getJSONObject(0);
              String http_replaced =
                  highest_res_pic.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            } else {
              // source property of the json object points to the photo's link
              String http_replaced = photo_json.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            }
          }

          download_photos.this.runOnUiThread(
              new Runnable() {
                public void run() {
                  //	mytask = new DownloadImageTask();
                  //	mytask.execute(links);
                  // start downloading using asynctask
                  // new DownloadImageTask().execute(links);
                  // downloadThread.setPath(path);
                  // downloadThread.setWholeTasks(links.size());
                  if (resume_file.exists()) {

                    initial_value = readProgress()[0];
                    final_value = links.size();
                    // case if the task is already completed
                    if (initial_value == final_value) {
                      completed = true;
                      resume_pause.setVisibility(View.GONE);

                      progress_download.setMax(final_value);
                      progress_download.setProgress(0); // bug in progress bar
                      progress_download.setProgress(initial_value);

                      progress_text.setText("Completed.");
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");

                    }

                    // case if some of the photos are already downloaded
                    else {
                      progress_download.setMax(links.size());
                      // progress_download.setProgress(0);	//bug in progress bar
                      progress_download.setProgress(initial_value);

                      // N.B if i= initial_value -1, then one image will be downloaded again. so to
                      // save cost we start with i = initial_value
                      for (int i = initial_value; i < links.size(); i++) {
                        mtext.setText(
                            getText(R.string.download_textview_message_1)
                                + " "
                                + path.toString()
                                + ". ");
                        // downloadThread.setRunningTask(i + 1);
                        downloadThread.enqueueDownload(
                            new DownloadTask(
                                links.get(i), path, i + 1, final_value, download_photos.this));
                      }
                    }
                  }

                  // case if the task is entirely new task
                  else {
                    for (int i = 0; i < links.size(); i++) {
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");
                      // downloadThread.setRunningTask(i + 1);
                      downloadThread.enqueueDownload(
                          new DownloadTask(
                              links.get(i), path, i + 1, links.size(), download_photos.this));
                    }
                  }
                }
              });
        } catch (JSONException ex) {
          Log.e(TAG, "JSONEXception : " + ex.getMessage());
        }
      }
    }

    // makes asynchronous request to facebook graph api
    // the actions to be performed after receiving json response is implemented above

    Bundle parameters = new Bundle();

    // facebook returns only 25 photos when limit is not specified.
    parameters.putString("limit", max_photos_in_album);
    if (!completed) mAsyncRunner.request(album_id + "/photos", parameters, new meRequestListener());

    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          permissions,
          new DialogListener() {

            // save fb access token and its expiry values to prefernces of this activity
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
            }

            @Override
            public void onFacebookError(FacebookError error) {
              Log.e(TAG, "Facebook Error : " + error.getMessage());
            }

            @Override
            public void onError(DialogError e) {
              Log.e(TAG, e.getMessage());
            }

            @Override
            public void onCancel() {
              // do nothing LOL :-)
            }
          });
    }
  }
예제 #16
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.context = this;
    setContentView(R.layout.main);

    // Without application id further processing cannot happen. APP_ID can be obtained from the
    // developers.facebook/apps page.
    if (APP_ID == null) {
      Util.showAlert(context, "Error", "Facebook application id is required");
    }

    // Facebook sesssion initialization
    mFacebook = new Facebook(APP_ID);

    // Check if previously obtained access token exists, in which case use the same.
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) {
      mFacebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      mFacebook.setAccessExpires(expires);
    }

    // Authentication from previously fetched accessed token
    if (mFacebook.isSessionValid()) {
      makeToast("Authorization complete. Values fetched from preferences");
      Bundle params = new Bundle();
      params.putString("fields", "name,id");
      mAsyncRunner = new AsyncFacebookRunner(mFacebook);
      mAsyncRunner.request("me", params, new UserRequestListener());
    }

    // Only call authorize if the access_token has expired.
    if (!mFacebook.isSessionValid()) {
      mFacebook.authorize(
          this,
          PERMISSIONS,
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", mFacebook.getAccessToken());
              editor.putLong("access_expires", mFacebook.getAccessExpires());
              editor.commit();

              // Authorization complete after fetching new token from facebook
              makeToast("Authorization complete. Connected to Facebook servers");

              Bundle params = new Bundle();
              params.putString("fields", "name,id");
              mAsyncRunner = new AsyncFacebookRunner(mFacebook);
              mAsyncRunner.request("me", params, new UserRequestListener());
            }

            @Override
            public void onFacebookError(FacebookError error) {
              makeToast(error.getMessage());
            }

            @Override
            public void onError(DialogError e) {
              makeToast(e.getMessage());
            }

            @Override
            public void onCancel() {
              makeToast("Exception in onCancel()");
            }
          });
    }
  }
예제 #17
0
  @Override
  public PluginResult execute(String action, JSONArray args, final String callbackId) {
    PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
    pr.setKeepCallback(true);

    if (action.equals("init")) {
      try {
        facebook = new Facebook(args.getString(0));

        Log.d("PhoneGapLog", "reauthorize");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.ctx);
        String access_token = prefs.getString("access_token", null);
        Long expires = prefs.getLong("access_expires", -1);

        if (access_token != null && expires != -1) {
          this.facebook.setAccessToken(access_token);
          this.facebook.setAccessExpires(expires);
          try {
            JSONObject o = new JSONObject(this.facebook.request("/me"));
            this.userId = o.getString("id");
          } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }

        if (facebook.isSessionValid() && this.userId != null) {
          return new PluginResult(PluginResult.Status.OK, this.getResponse());
        } else {
          return new PluginResult(PluginResult.Status.NO_RESULT);
        }
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return new PluginResult(
            PluginResult.Status.ERROR,
            "Invalid JSON args used. expected a string as the first arg.");
      }
    } else if (action.equals("login")) {
      if (facebook != null) {
        if (facebook.isSessionValid()) {
          Log.d("FB", "Session already valid");
          pr = new PluginResult(PluginResult.Status.OK, getResponse());
        } else {
          final ConnectPlugin me = this;
          String[] permissions = new String[args.length()];
          try {
            for (int i = 0; i < args.length(); i++) {
              permissions[i] = args.getString(i);
            }
          } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return new PluginResult(
                PluginResult.Status.ERROR,
                "Invalid JSON args used. Expected a string array of permissions.");
          }

          this.ctx.setActivityResultCallback(this);
          this.permissions = permissions;
          this.callbackId = callbackId;
          Runnable runnable =
              new Runnable() {
                public void run() {
                  me.facebook.authorize(
                      (Activity) me.ctx, me.permissions, new AuthorizeListener(me));
                };
              };
          this.ctx.runOnUiThread(runnable);
        }
      } else {
        pr = new PluginResult(PluginResult.Status.ERROR, "Must call FB.init before FB.login");
      }
    } else if (action.equals("logout")) {
      if (facebook != null) {
        try {
          facebook.logout(this.ctx);

          SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.ctx);
          prefs.edit().putLong("access_expires", -1).commit();
          prefs.edit().putString("access_token", null).commit();
        } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          pr = new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "Error logging out.");
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          pr = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Error logging out.");
        }
        pr = new PluginResult(PluginResult.Status.OK, getResponse());
      }
    } else if (action.equals("getLoginStatus")) {
      if (facebook != null) {
        pr = new PluginResult(PluginResult.Status.OK, getResponse());
      }
    }

    return pr;
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
      Util.showAlert(
          this,
          "Warning",
          "Facebook Applicaton ID must be "
              + "specified before running this example: see FacebookInterfaceActivity.java");
    }

    setContentView(R.layout.facebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) FacebookInterfaceActivity.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, mFacebook);

    mRequestButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
          }
        });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
              uploadFileUrl =
                  new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
              e.printStackTrace();
            }
            try {
              HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
              conn.setDoInput(true);
              conn.connect();
              int length = conn.getContentLength();

              byte[] imgData = new byte[length];
              InputStream is = conn.getInputStream();
              is.read(imgData);
              params.putByteArray("picture", imgData);

            } catch (IOException e) {
              e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
          }
        });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            mFacebook.dialog(FacebookInterfaceActivity.this, "feed", new SampleDialogListener());
          }
        });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
  }