Java tutorial
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.hellofacebook; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.facebook.AppEventsLogger; import com.facebook.FacebookAuthorizationException; import com.facebook.FacebookOperationCanceledException; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.model.GraphPlace; import com.facebook.model.GraphUser; import com.facebook.widget.FacebookDialog; import com.facebook.widget.FriendPickerFragment; import com.facebook.widget.LoginButton; import com.facebook.widget.PickerFragment; import com.facebook.widget.PlacePickerFragment; import com.facebook.widget.ProfilePictureView; public class MapFriends extends FragmentActivity { private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction"; private ProfilePictureView profilePictureView; private TextView greeting; private PendingAction pendingAction = PendingAction.NONE; private ViewGroup controlsContainer; private GraphUser user; private enum PendingAction { NONE, POST_PHOTO, POST_STATUS_UPDATE } private UiLifecycleHelper uiHelper; private Button gotoMapButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(this, callback); uiHelper.onCreate(savedInstanceState); getKeyHash(); if (savedInstanceState != null) { String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY); pendingAction = PendingAction.valueOf(name); } setContentView(R.layout.main); LoginButton loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setReadPermissions( Arrays.asList("user_friends", "user_location", "friends_location", "friends_hometown")); loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() { @Override public void onUserInfoFetched(GraphUser user) { MapFriends.this.user = user; updateUI(); } }); profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture); greeting = (TextView) findViewById(R.id.greeting); gotoMapButton = (Button) findViewById(R.id.gotoMap); gotoMapButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent intent = new Intent(MapFriends.this, MapDetails.class); startActivity(intent); } }); controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container); final FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment != null) { // If we're being re-created and have a fragment, we need to a) hide the main UI controls and // b) hook up its listeners again. controlsContainer.setVisibility(View.GONE); if (fragment instanceof FriendPickerFragment) { setFriendPickerListeners((FriendPickerFragment) fragment); } else if (fragment instanceof PlacePickerFragment) { setPlacePickerListeners((PlacePickerFragment) fragment); } } // Listen for changes in the back stack so we know if a fragment got popped off because the user // clicked the back button. fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { if (fm.getBackStackEntryCount() == 0) { // We need to re-show our UI. controlsContainer.setVisibility(View.VISIBLE); } } }); FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG); } private void getKeyHash() { try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (NameNotFoundException e) { Log.d("getKeyHash()", "NameNotFoundException"); } catch (NoSuchAlgorithmException e) { Log.d("getKeyHash()", "NoSuchAlgorithmException"); } } private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onSessionStateChange(session, state, exception); } }; private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() { @Override public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) { Log.d("HelloFacebook", String.format("Error: %s", error.toString())); } @Override public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) { Log.d("HelloFacebook", "Success!"); } }; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiHelper.onSaveInstanceState(outState); outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name()); } private void onSessionStateChange(Session session, SessionState state, Exception exception) { if (pendingAction != PendingAction.NONE && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) { new AlertDialog.Builder(MapFriends.this).setTitle(R.string.cancelled) .setMessage(R.string.permission_not_granted).setPositiveButton(R.string.ok, null).show(); pendingAction = PendingAction.NONE; } else if (state == SessionState.OPENED_TOKEN_UPDATED) { // handlePendingAction(); } updateUI(); } private void updateUI() { Session session = Session.getActiveSession(); boolean enableButtons = (session != null && session.isOpened()); gotoMapButton.setEnabled(enableButtons); if (enableButtons && user != null) { profilePictureView.setProfileId(user.getId()); greeting.setText(getString(R.string.hello_user, user.getFirstName())); } else { profilePictureView.setProfileId(null); greeting.setText(null); } } private void setFriendPickerListeners(final FriendPickerFragment fragment) { fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() { @Override public void onDoneButtonClicked(PickerFragment<?> pickerFragment) { onFriendPickerDone(fragment); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback); } @Override public void onPause() { super.onPause(); uiHelper.onPause(); } @Override /** * Call the 'activateApp' method to log an app event for use in analytics and advertising reporting. * Do so in the onResume methods of the primary Activities that an app may be launched into. */ protected void onResume() { super.onResume(); uiHelper.onResume(); AppEventsLogger.activateApp(this); updateUI(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } private void onFriendPickerDone(FriendPickerFragment fragment) { FragmentManager fm = getSupportFragmentManager(); fm.popBackStack(); String results = ""; List<GraphUser> selection = fragment.getSelection(); if (selection != null && selection.size() > 0) { ArrayList<String> names = new ArrayList<String>(); for (GraphUser user : selection) { names.add(user.getName()); } results = TextUtils.join(", ", names); } else { results = getString(R.string.no_friends_selected); } showAlert(getString(R.string.you_picked), results); } private void onPlacePickerDone(PlacePickerFragment fragment) { FragmentManager fm = getSupportFragmentManager(); fm.popBackStack(); String result = ""; GraphPlace selection = fragment.getSelection(); if (selection != null) { result = selection.getName(); } else { result = getString(R.string.no_place_selected); } showAlert(getString(R.string.you_picked), result); } private void setPlacePickerListeners(final PlacePickerFragment fragment) { fragment.setOnDoneButtonClickedListener(new PlacePickerFragment.OnDoneButtonClickedListener() { @Override public void onDoneButtonClicked(PickerFragment<?> pickerFragment) { onPlacePickerDone(fragment); } }); fragment.setOnSelectionChangedListener(new PlacePickerFragment.OnSelectionChangedListener() { @Override public void onSelectionChanged(PickerFragment<?> pickerFragment) { if (fragment.getSelection() != null) { onPlacePickerDone(fragment); } } }); } private void showAlert(String title, String message) { new AlertDialog.Builder(this).setTitle(title).setMessage(message).setPositiveButton(R.string.ok, null) .show(); } }