Wednesday, June 22, 2011

How to integrate facebook in Android


private static final String FACEBOOK_APPID = "152426674829331";//219680308049221

private static final String FACEBOOK_PERMISSION = "publish_stream";

private static final String MSG = " Testing TalkUsage Application ";

private final Handler mFacebookHandler = new Handler();

private FacebookConnector mFacebookConnector;

final Runnable mUpdateFacebookNotification = new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), getString(R.string.facebookposted), TOASTTIME).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
this.mFacebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});
mFaceBook = (ImageView)findViewById(R.id.Facebook);
mFaceBook.setOnClickListener(mFaceBookListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.mFacebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
}

@Override
protected void onResume()
{
super.onResume();
clearCredentials();
}

private String getFacebookMsg()
{
return new Date().toLocaleString() + MSG;
}
public void postMessage()
{
if (mFacebookConnector.getFacebook().isSessionValid())
{
postMessageInThread();
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
@Override
public void onAuthSucceed()
{
postMessageInThread();
}

@Override
public void onAuthFail(String error)
{
Log.e(TAG, error);
}
};
SessionEvents.addAuthListener(listener);
mFacebookConnector.login();
}
}

private void postMessageInThread()
{
Thread mThread = new Thread()
{
public void run()
{
mFacebookConnector.postMessageOnWall(getFacebookMsg());
mFacebookHandler.post(mUpdateFacebookNotification);
clearCredentials();
}
};
mThread.start();
}

private void clearCredentials()
{
try
{
mFacebookConnector.getFacebook().logout(getApplicationContext());
}
catch (MalformedURLException mMalformedURLException)
{
Log.e(TAG, getString(R.string.malformedurlexceptionerror) + mMalformedURLException.toString());
}
catch (IOException mIOException)
{
Log.e(TAG, getString(R.string.ioexceptionerror) + mIOException.toString());
}
}
private OnClickListener mFaceBookListener = new OnClickListener()
{
public void onClick(View v)
{
postMessage();
}
};

No comments:

Post a Comment