/** 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()); } }
/** * 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())); } }
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 } }); } }
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.exit) { // close the Activity this.finish(); return true; } else if (item.getItemId() == R.id.facebook) { facebook.authorize( this, new String[] { "user_checkins", "friends_checkins", "publish_checkins", "email", "publish_stream", "read_stream", "offline_access" }, new DialogListener() { @Override public void onComplete(Bundle values) { Log.i("accesstoken =", "" + facebook.getAccessToken()); } @Override public void onFacebookError(FacebookError error) {} @Override public void onError(DialogError e) {} @Override public void onCancel() {} }); return true; } else if (item.getItemId() == R.id.note) { tracker.trackPageView("/Notes"); Intent intent = new Intent(MainActivity.this, NotesList.class); startActivity(intent); return true; } else if (item.getItemId() == R.id.photo) { tracker.trackPageView("/Photos"); Intent intent = new Intent(MainActivity.this, PhotoActivity.class); startActivity(intent); return true; } else if (item.getItemId() == R.id.voice) { tracker.trackPageView("/Voices"); Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(intent, RQS_RECORDING); } return false; }
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(); }
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); } }
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 } }); } }
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..."); } }); } }
public void button_session_register_fbk_onClick(View view) { final Activity thisActivity = this; facebook.authorize( this, PERMS, new DialogListener() { @Override public void onComplete(Bundle values) { final String token = facebook.getAccessToken(); // intentar iniciar sesión SessionController.getInstance() .loginExternal( "facebook", token, new OnCompletedCallback() { @Override public void onCompleted(String response, String error) { if (error != null) { CommonUtilities.showAlertMessage( SessionLoginActivity.this, "Error SLA bloc", error); } else { onLoginSuccess(true); } } }); } @Override public void onFacebookError(FacebookError error) {} @Override public void onError(DialogError e) {} @Override public void onCancel() {} }); }
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 } }); } }
/** * Authorize method that grants custom permissions. * * <p>See authorize() below for @params. */ public void authorize(Activity activity, String[] permissions, final DialogListener listener) { authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, listener); }
/** * Default authorize method. Grants only basic permissions. * * <p>See authorize() below for @params. */ public void authorize(Activity activity, final DialogListener listener) { authorize(activity, new String[] {}, DEFAULT_AUTH_ACTIVITY_CODE, listener); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean fetchProfile = getIntent().getBooleanExtra("fetchProfile", true); final boolean isFacebook = getIntent().getBooleanExtra("isfacebook", false); final String photoPath = getIntent().getStringExtra("Photo"); final String albumName = getIntent().getStringExtra("Album"); final String addComments = getIntent().getStringExtra("AddComments"); final String likes = getIntent().getStringExtra("Likes"); final String unLikes = getIntent().getStringExtra("Unlikes"); final String photoId = getIntent().getStringExtra("PhotoId"); final String comments = getIntent().getStringExtra("Comments"); if (isFacebook) { facebook.authorize( this, new String[] {"user_photos,publish_checkins,publish_actions,publish_stream"}, new DialogListener() { @Override public void onComplete(Bundle values) { FacebookSocialNetwork socialNetwork = new FacebookSocialNetwork( Phlogit .getPhlogitApplicationContext()); // (FacebookSocialNetwork)SocialNetwork.getProvider(SocialNetwork.SOCIAL_NETWORK_FACEBOOK); socialNetwork.setTokens( facebook.getAccessToken(), (values != null ? values.get("id") : null), facebook.getAccessExpires()); socialNetwork.fetchProfile(); if (!TextUtils.isEmpty(photoPath)) { socialNetwork.uploadPhoto(photoPath, albumName, null); } else if ("true".equals(addComments)) { socialNetwork.addComment(photoId, comments); Toast.makeText(WebViewClientActivity.this, "Comments added", Toast.LENGTH_LONG) .show(); } else if ("true".equals(likes)) { socialNetwork.like(photoId); Toast.makeText(WebViewClientActivity.this, "Photo Liked", Toast.LENGTH_LONG).show(); } else if ("true".equals(unLikes)) { socialNetwork.unLike(photoId); Toast.makeText(WebViewClientActivity.this, "Photo Unliked", Toast.LENGTH_LONG) .show(); } finish(); } @Override public void onCancel() { Toast.makeText(WebViewClientActivity.this, "Cancel!", Toast.LENGTH_LONG).show(); } @Override public void onFacebookError(FacebookError e) { Toast.makeText(WebViewClientActivity.this, "FacebookError " + e, Toast.LENGTH_LONG) .show(); } @Override public void onError(DialogError e) { Toast.makeText(WebViewClientActivity.this, "Error " + e, Toast.LENGTH_LONG).show(); } }); } else { setContentView(R.layout.webview_activity); String authUrl = getIntent().getStringExtra("authUrl"); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); WebSettings websettings = webview.getSettings(); websettings.setLoadWithOverviewMode(true); websettings.setJavaScriptEnabled(true); webview.setWebViewClient( new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onLoadResource(WebView view, String url) { // Twitter if (url.startsWith("http://appsforandroid.blogspot.com")) { Uri uri = Uri.parse(url); String verifier = uri.getQueryParameter("oauth_verifier"); TwitterSocialNetwork socialNetwork = (TwitterSocialNetwork) SocialNetwork.getProvider(SocialNetwork.SOCIAL_NETWORK_TWITTER); socialNetwork.setTokens(verifier); socialNetwork.fetchProfile(); finish(); } } }); webview.loadUrl(authUrl); } }
@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()"); } }); } }
@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 :-) } }); } }