Code example for Activity

Methods: startActivityForResult, isFinishing

0
		} 
	} 
	 
	private void show(){ 
		if(dialog != null){		
			new AQuery(act).show(dialog);
		} 
	} 
	 
	private void hide(){ 
		if(dialog != null){
			try{ 
				dialog.hide();
			}catch(Exception e){
				AQUtility.debug(e);
			} 
		} 
	} 
	 
	private void failure(){ 
		failure("cancel"); 
	} 
	 
	 
	private void failure(String message){
		dismiss(); 
		failure(act, AjaxStatus.AUTH_ERROR, message);
	} 
	 
	protected void auth() { 
		 
		if(act.isFinishing()) return;
		 
		 
		boolean ok = sso();
		 
		AQUtility.debug("authing", ok);
		 
		 
		if(!ok){
			webAuth(); 
		} 
		 
	} 
	 
	private boolean sso(){ 
		 
		if(!sso) return false;
		return startSingleSignOn(act, appId, permissions, requestId);
		 
	} 
	 
	private void webAuth() { 
 
		AQUtility.debug("web auth"); 
		 
		Bundle parameters = new Bundle();
		parameters.putString("client_id", appId);
		parameters.putString("type", "user_agent");
		if(permissions != null){
			parameters.putString("scope", permissions);
		} 
		 
		parameters.putString("redirect_uri", REDIRECT_URI);
		String url = OAUTH_ENDPOINT + "?" + encodeUrl(parameters);
		 
		FbWebViewClient client = new FbWebViewClient();
		 
		dialog = new WebDialog(act, url, client);	
		dialog.setLoadingMessage(message);
		dialog.setOnCancelListener(client);
		 
		show(); 
		 
		if(!first || token != null){
			 
			AQUtility.debug("auth hide"); 
			hide(); 
			 
		} 
		 
		dialog.load();
		 
		AQUtility.debug("auth started"); 
	} 
	 
	private static final String FB_TOKEN = "aq.fb.token";
	private static final String FB_PERMISSION = "aq.fb.permission";
	 
	private String fetchToken(){
		return PreferenceManager.getDefaultSharedPreferences(act).getString(FB_TOKEN, null);	
	} 
	 
	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;