Code example for Activity

Methods: getDefaultSharedPreferences

0
	private String fetchPermission(){
		return PreferenceManager.getDefaultSharedPreferences(act).getString(FB_PERMISSION, null);	
	} 
	 
	private void storeToken(String token, String permission){
		Editor editor = PreferenceManager.getDefaultSharedPreferences(act).edit();
		editor.putString(FB_TOKEN, token).putString(FB_PERMISSION, permission);//.commit();	
		AQUtility.apply(editor);
	} 
	 
	private class FbWebViewClient extends WebViewClient implements OnCancelListener {
		 
		private boolean checkDone(String url){
			 
			if(url.startsWith(REDIRECT_URI)) {
				 
				Bundle values = parseUrl(url);
				 
				String error = values.getString("error_reason");
				 
				AQUtility.debug("error", error);
				 
				 
				if(error == null) {
					token = extractToken(url);					
				} 
				 
				if(token != null){
					dismiss(); 
					storeToken(token, permissions);
					first = false;
					authenticated(token);
					success(act);
				}else{ 
					failure(); 
				} 
				 
				return true; 
			}else if(url.startsWith(CANCEL_URI)) {
				AQUtility.debug("cancelled"); 
				failure(); 
				return true; 
			}  
			 
			return false; 
		} 
		 
		 
		@Override 
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			 
			AQUtility.debug("return url: " + url);
			 
			return checkDone(url);
			 
		} 
		 
		@Override 
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			 
			AQUtility.debug("started", url);
			 
			if(checkDone(url)){
			}else{			 
				super.onPageStarted(view, url, favicon);
			} 
			 
		} 
		 
		@Override 
		public void onPageFinished(WebView view, String url) {
			 
			super.onPageFinished(view, url);			
			show(); 
			 
			AQUtility.debug("finished", url);
		} 
		 
		 
		@Override 
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			failure(); 
		} 
		 
 
		@Override 
		public void onCancel(DialogInterface dialog) {
			failure(); 
		} 
		 
	} 
 
	 
	private String extractToken(String url) {
 
		Uri uri = Uri.parse(url.replace('#', '?'));
 
		String token = uri.getQueryParameter("access_token");
 
		AQUtility.debug("token", token);
 
		return token;
		 
		 
	} 
 
	private static String encodeUrl(Bundle parameters) {
		if (parameters == null) {
			return ""; 
		} 
		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for (String key : parameters.keySet()) {
			if (first)
				first = false;
			else 
				sb.append("&");
			sb.append(key + "=" + parameters.getString(key));
		} 
		return sb.toString();
	} 
 
	private static Bundle decodeUrl(String s) {
		Bundle params = new Bundle();
		if (s != null) {
			String array[] = s.split("&");
			for (String parameter : array) {
				String v[] = parameter.split("=");
				params.putString(v[0], v[1]);
			} 
		} 
		return params;
	} 
 
	 
	private static Bundle parseUrl(String url) {
		 
		try { 
			URL u = new URL(url);
			Bundle b = decodeUrl(u.getQuery());
			b.putAll(decodeUrl(u.getRef()));
			return b;
		} catch (MalformedURLException e) {
			return new Bundle();
		} 
	} 
 
	//03-17 17:05:40.594: W/AQuery(23190): error:{"error":{"message":"Error validating access token: User 1318428934 has not authorized application 155734287864315.","type":"OAuthException","code":190}} 
 
	@Override 
	public boolean expired(AbstractAjaxCallback<?, ?> cb, AjaxStatus status) {
		 
		int code = status.getCode();
		if(code == 200) return false;
		 
		String error = status.getError();
		if(error != null && error.contains("OAuthException")){
			AQUtility.debug("fb token expired"); 
			return true; 
		} 
		 
		String url = cb.getUrl();
		 
		if(code == 400 && (url.endsWith("/likes") || url.endsWith("/comments") || url.endsWith("/checkins"))){
			return false; 
		} 
		 
		if(code == 403 && (url.endsWith("/feed") || url.contains("method=delete"))){
			return false; 
		} 
		 
		return code == 400 || code == 401 || code == 403;
	} 
 
	@Override 
	public boolean reauth(final AbstractAjaxCallback<?, ?> cb) {
		 
		AQUtility.debug("reauth requested"); 
		 
		token = null;
		 
		AQUtility.post(new Runnable() {
			 
			@Override 
			public void run() { 
				auth(cb);
			} 
		}); 
		 
		return false; 
	} 
 
	 
	@Override 
	public String getNetworkUrl(String url){
 
		if(url.indexOf('?') == -1){
			url = url + "?";
		}else{ 
			url = url + "&";
		} 
		 
		url = url + "access_token=" + token;
		return url;
	} 
	 
	@Override 
	public String getCacheUrl(String url){
		return getNetworkUrl(url);
	} 
 
 
	@Override 
	public boolean authenticated() { 
		 
		return token != null;
	} 
	 
	@Override 
	public void unauth(){ 
		 
		token = null;
		 
		CookieSyncManager.createInstance(act);
		CookieManager.getInstance().removeAllCookie();	
		storeToken(null, null); 
	} 
	 
    private boolean startSingleSignOn(Activity activity, String applicationId, String permissions, int activityCode) {
         
    	boolean didSucceed = true;
        Intent intent = new Intent();
 
        intent.setClassName("com.facebook.katana", "com.facebook.katana.ProxyAuth");
        intent.putExtra("client_id", applicationId);
         
        if(permissions != null) {
            intent.putExtra("scope", permissions);
        } 
 
        if(!validateAppSignatureForIntent(activity, intent)){
            return false; 
        } 
 
        try { 
            activity.startActivityForResult(intent, activityCode);
        } catch (ActivityNotFoundException e) {
            didSucceed = false;
        } 
 
        return didSucceed;
    } 
     
    private static Boolean hasSSO;
     
    public boolean isSSOAvailable(){ 
    	 
    	if(hasSSO == null){
    		Intent intent = new Intent();
    		intent.setClassName("com.facebook.katana", "com.facebook.katana.ProxyAuth");
    		hasSSO = validateAppSignatureForIntent(act, intent);
    	} 
    	 
    	return hasSSO;
    } 
     
	protected void authenticated(String token){
		 
	} 
     
	public void ajaxProfile(AjaxCallback<JSONObject> cb){
		ajaxProfile(cb, 0);
	} 
 
    public void ajaxProfile(AjaxCallback<JSONObject> cb, long expire){
    	 
		String url = "https://graph.facebook.com/me";
		 
		AQuery aq = new AQuery(act);	
		aq.auth(this).ajax(url, JSONObject.class, expire, cb);
     
    } 
     
    private boolean validateAppSignatureForIntent(Context context, Intent intent) {
 
    	PackageManager pm = context.getPackageManager();
    	 
        ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
        if(resolveInfo == null){
            return false; 
        } 
 
        String packageName = resolveInfo.activityInfo.packageName;
        PackageInfo packageInfo;
        try { 
            packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        } catch (NameNotFoundException e) {
            return false; 
        } 
 
        for(Signature signature : packageInfo.signatures) {
            if(signature.toCharsString().equals(FB_APP_SIGNATURE)) {
                return true; 
            } 
        } 
        return false; 
    } 
     
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
         
    	AQUtility.debug("on result", resultCode);
    	 
        // Successfully redirected. 
        if (resultCode == Activity.RESULT_OK) {
 
            // Check OAuth 2.0/2.10 error code. 
            String error = data.getStringExtra("error");
            if (error == null) {
                error = data.getStringExtra("error_type");
            } 
 
            
            // A Facebook error occurred. 
            if(error != null) {
            	AQUtility.debug("error", error);
            	if(error.equals("service_disabled") || error.equals("AndroidAuthKillSwitchException")) {
            		webAuth(); 
                }else{                	 
                	 
                	String description = data.getStringExtra("error_description");
                    AQUtility.debug("fb error", description);
                    Log.e("fb error", description);       	
                	failure(description);
                } 
            // No errors. 
            }else{ 
            	 
            	token = data.getStringExtra("access_token");
            	 
            	AQUtility.debug("onComplete", token);
				if(token != null){
					storeToken(token, permissions);
					first = false;
					authenticated(token);
					success(act);
				}else{ 
					failure(); 
				} 
            	 
            }