Search This Blog

Sunday, 31 July 2011

Android Use Open Id in application.

Manifest.xml

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

    </application>

<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.USE_CREDENTIALS"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

AccountList.java

package net.notdot.aeauth;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AccountList extends ListActivity {
protected AccountManager accountManager;
protected Intent intent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        accountManager = AccountManager.get(getApplicationContext());
        Account[] accounts = accountManager.getAccountsByType("com.google");
        this.setListAdapter(new ArrayAdapter<Account>(this, R.layout.list_item, accounts));      
    }

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Account account = (Account)getListView().getItemAtPosition(position);
Intent intent = new Intent(this, AppInfo.class);
intent.putExtra("account", account);
startActivity(intent);
}
}


AppInfo.java

package net.notdot.aeauth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

public class AppInfo extends Activity {
DefaultHttpClient http_client = new DefaultHttpClient();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_info);
}

@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
AccountManager accountManager = AccountManager.get(getApplicationContext());
Account account = (Account)intent.getExtras().get("account");
accountManager.getAuthToken(account, "ah", false, new GetAuthTokenCallback(), null);
}

private class GetAuthTokenCallback implements AccountManagerCallback<Bundle> {
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = result.getResult();
Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT);
if(intent != null) {
// User input required
startActivity(intent);
} else {
onGetAuthToken(bundle);
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};

protected void onGetAuthToken(Bundle bundle) {
String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
new GetCookieTask().execute(auth_token);
}

private class GetCookieTask extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

HttpGet http_get = new HttpGet("https://yourapp.appspot.com/_ah/login?continue=http://localhost/&auth=" + tokens[0]);
HttpResponse response;
response = http_client.execute(http_get);
if(response.getStatusLine().getStatusCode() != 302)
// Response should be a redirect
return false;

for(Cookie cookie : http_client.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID"))
return true;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}

protected void onPostExecute(Boolean result) {
new AuthenticatedRequestTask().execute("http://yourapp.appspot.com/admin/");
}
}

private class AuthenticatedRequestTask extends AsyncTask<String, Void, HttpResponse> {
@Override
protected HttpResponse doInBackground(String... urls) {
try {
HttpGet http_get = new HttpGet(urls[0]);
return http_client.execute(http_get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

protected void onPostExecute(HttpResponse result) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(result.getEntity().getContent()));
String first_line = reader.readLine();
Toast.makeText(getApplicationContext(), first_line, Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


Layout Files : - 
app_info.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="@string/hello"/>


list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>


No comments:

Post a Comment