Sabtu, 05 Januari 2013

Membuat Aplikasi Android Connect ke Facebook, Android Update Status Facebook

Aplikasi yang akan kita buat kali ini cukup menarik, yaitu Update Status Facebook dengan Aplikasi Android
Pertama kita download dahulu Facebook Android SDK dari link berikut

Kemudian extract dan Import ke Eclipse, caranya klik File-Import, Existing Projects into Workspace, kemudian pilih facebook-android-sdk.



Langkah berikutnya kita generate KeyHash atau Application Signature dari Project kita dengan buat memakai keytool yang telah tersedia dari JDK yang sudah terinstall di komputer Anda. kemudian ditambah software OpenSSL yang dapat didownload di link berikut.

Buka command DOS prompt, klik Start-Run, ketik perintah berikut :



<lokasi jdk>\bin\keytool.exe -exportcert keystore | <lokasi program openSSL>\bin\openssl.exe sha1 -binary | <lokasi program openSSL>\bin\openssl.exe base64 

Enter keystore password : android



Kemudian setelah mendapatkan key yang diinginkan catat, simpan baik-baik untuk dimasukkan ke Facebook Application Developer Setting.


Setelah itu login terlebih dahulu ke Facebook untuk mendaftarkan aplikasi yang akan dibuat, klik link berikut untuk masuk ke Facebook Application Developer.

Daftarkan sebuah aplikasi yang akan kita buat, pilih bertipe Android Application. Kemudian masukkan Hash Key yang tadi dapatkan.


Kemudian didapatkan App ID, catat dan simpan baik-baik untuk dipakai di kode program pada Project Android.

Buat project baru di Eclipse. Kemudian klik Project-Properties, pilih Tab Android, Library klik Add. Pilih com_facebook_sdk.


Pada MainActivity kita panggil dan gunakan Facebook SDK dengan Kode Program berikut :

package com.amijaya.androidfacebookapplication;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MainActivity extends Activity {

// Your Facebook APP ID
private static String APP_ID = "101913803286982"; // Replace with your App ID

// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;

// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
mAsyncRunner = new AsyncFacebookRunner(facebook);

/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});

/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
getProfileInformation();
}
});

/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
postToWall();
}
});

/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
showAccessTokens();
}
});

}

/**
* Function to login into facebook
* */
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);

btnFbLogin.setVisibility(View.INVISIBLE);

// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);

Log.d("FB Sessions", "" + facebook.isSessionValid());
}

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();

// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);

// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
}

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

}

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

}

});
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}


/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);

// getting name of the user
final String name = profile.getString("name");

// getting email of the user
final String email = profile.getString("email");

runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}

});


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

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {

@Override
public void onFacebookError(FacebookError e) {
}

@Override
public void onError(DialogError e) {
}

@Override
public void onComplete(Bundle values) {
}

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

}

/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();

Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}

/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {

@Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);

// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
}

});

}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

}

Kemudian untuk tampilan kita pakai layout default dari main.xml ditambah tiga button seperti ini :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="#f0f0f0">
    
    <!-- Facebook Login Button -->
    <Button android:id="@+id/btn_fblogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dip"
        android:layout_gravity="center_horizontal"
        android:text="Login with Facebook"/>
   
    
    <!-- Facebook Post to Wall Button -->
    <Button android:id="@+id/btn_fb_post_to_wall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post to Wall"
        android:layout_marginTop="30dip"
        android:layout_gravity="center_horizontal"
        android:visibility="gone"/>
    <!-- Facebook Logout Button -->
    <Button android:id="@+id/btn_get_profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Profile Data"
        android:layout_marginTop="30dip"
        android:layout_gravity="center_horizontal"
        android:visibility="gone"/>
    
    <!-- Button to show access tokens -->
    <Button android:id="@+id/btn_show_access_tokens"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Access Tokens"
        android:layout_marginTop="30dip"
        android:layout_gravity="center_horizontal"
        android:visibility="gone"/>
    

</LinearLayout>

Jangan lupa memberi permission INTERNET pada AndroidManifest.xml agar dapat terhubung ke Server Facebook :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amijaya.androidfacebookapplication"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Hasilnya, kita bisa mengupdate Status Facebook via Android Application :







Source Code selengkapnya dapat didownload pada link berikut.

Setelah masuk Google Drive, klik pojok kiri atas, File-Download.

Selamat Mencoba, semoga berhasil.