Thứ Tư, 17 tháng 9, 2014

Ví dụ dùng facebook sdk example android

package com.javatechig.fbsample;

import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;

public class FBActivity extends FragmentActivity {

	private LoginButton loginBtn;
	private Button postImageBtn;
	private Button updateStatusBtn;

	private TextView userName;

	private UiLifecycleHelper uiHelper;

	private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");

	private static String message = "Sample status posted from android app";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		uiHelper = new UiLifecycleHelper(this, statusCallback);
		uiHelper.onCreate(savedInstanceState);

		setContentView(R.layout.activity_facebook);

		userName = (TextView) findViewById(R.id.user_name);
		loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
		loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
			@Override
			public void onUserInfoFetched(GraphUser user) {
				if (user != null) {
					userName.setText("Hello, " + user.getName());
				} else {
					userName.setText("You are not logged");
				}
			}
		});

		postImageBtn = (Button) findViewById(R.id.post_image);
		postImageBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				postImage();
			}
		});

		updateStatusBtn = (Button) findViewById(R.id.update_status);
		updateStatusBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

		buttonsEnabled(false);
	}

	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			if (state.isOpened()) {
				buttonsEnabled(true);
				Log.d("FacebookSampleActivity", "Facebook session opened");
			} else if (state.isClosed()) {
				buttonsEnabled(false);
				Log.d("FacebookSampleActivity", "Facebook session closed");
			}
		}
	};

	public void buttonsEnabled(boolean isEnabled) {
		postImageBtn.setEnabled(isEnabled);
		updateStatusBtn.setEnabled(isEnabled);
	}

	public void postImage() {
		if (checkPermissions()) {
			Bitmap img = BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_launcher);
			Request uploadRequest = Request.newUploadPhotoRequest(
					Session.getActiveSession(), img, new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							Toast.makeText(FBActivity.this,
									"Photo uploaded successfully",
									Toast.LENGTH_LONG).show();
						}
					});
			uploadRequest.executeAsync();
		} else {
			requestPermissions();
		}
	}

	public void postStatusMessage() {
		if (checkPermissions()) {
			Request request = Request.newStatusUpdateRequest(
					Session.getActiveSession(), message,
					new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							if (response.getError() == null)
								Toast.makeText(FBActivity.this,
										"Status updated successfully",
										Toast.LENGTH_LONG).show();
						}
					});
			request.executeAsync();
		} else {
			requestPermissions();
		}
	}

	public boolean checkPermissions() {
		Session s = Session.getActiveSession();
		if (s != null) {
			return s.getPermissions().contains("publish_actions");
		} else
			return false;
	}

	public void requestPermissions() {
		Session s = Session.getActiveSession();
		if (s != null)
			s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
					this, PERMISSIONS));
	}

	@Override
	public void onResume() {
		super.onResume();
		uiHelper.onResume();
		buttonsEnabled(Session.getActiveSession().isOpened());
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

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

	@Override
	public void onSaveInstanceState(Bundle savedState) {
		super.onSaveInstanceState(savedState);
		uiHelper.onSaveInstanceState(savedState);
	}

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="20dp" >

    <com.facebook.widget.LoginButton
        android:id="@+id/fb_login_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        facebook:confirm_logout="false"
        facebook:fetch_user_info="true" />

    <TextView
        android:id="@+id/user_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:textSize="18sp" />

    <Button
        android:id="@+id/update_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/update_status" />

    <Button
        android:id="@+id/post_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/post_image" />

</LinearLayout>


Sử dụng facebook trong android

Cách post tới wall với object facebook:
private void postToWall()
{
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);

Bundle params = new Bundle();
   
params.putString("message", "sdsddsdsd");
params.putString("name", "Dexter");
params.putString("caption", "londatiga.net");
params.putString("link", "http://www.londatiga.net");
params.putString("description", "Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk");
params.putString("picture", "http://twitpic.com/show/thumb/6hqd44");

mAsyncFbRunner.request("me/feed", params,"POST",new WallPostListener(),new Object());
}

private final class WallPostListener implements AsyncFacebookRunner.RequestListener {

@Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.d("phanbom", "Test response ne:"+response);

}

@Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub

}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub

}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub

}

@Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub

}
 }

Đây là code khởi động việc login:

mFacebook.authorize(this, PERMISSIONS, -1, new FbLoginDialogListener());
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    mFacebook.authorizeCallback(requestCode, resultCode, data);
    }
    private final class FbLoginDialogListener implements DialogListener {

@Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Log.d("phanbom", "facebook ne");
            SessionStore.save(mFacebook, TestConnect.this);
            mFacebookBtn.setText("  Facebook (No Name)");
            mFacebookBtn.setChecked(true);
mFacebookBtn.setTextColor(Color.WHITE);
 
            getFbName();
}

@Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
          
          mFacebookBtn.setChecked(false);
}

@Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show(); 
       
        mFacebookBtn.setChecked(false);
}

@Override
public void onCancel() {
// TODO Auto-generated method stub
mFacebookBtn.setChecked(false);
}

    }

Đây là code post status nhờ vào token đã đăng nhập từ trước , sử dụng cách của phiên bản facebook sdk 3.0 trở lên:

SharedPreferences savedSession = getApplicationContext().getSharedPreferences(SessionStore.KEY, Context.MODE_PRIVATE);

Date date=null;
        try {
            date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(savedSession.getString(SessionStore.EXPIRES,"0"));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
token = AccessToken.createFromExistingAccessToken(savedSession.getString(SessionStore.TOKEN, null),date, null, AccessTokenSource.TEST_USER, null);


public void postNew()
{
Session.openActiveSessionWithAccessToken(this,token,new Session.StatusCallback() {

@Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
            // callback when session changes state
  if (session.isOpened()) {


                       // make request to the /me API
                       Request.newMeRequest(session, new Request.GraphUserCallback() {

                         // callback after Graph API response with user object
                         @Override
                         public void onCompleted(GraphUser user, Response response) {
                           if (user != null) {
                          Log.d("phanbom","tiep theo ne:"+user.getName()+"|"+user.getUsername());
                  
                           }
                         }
         }).executeAsync();
                       GraphPlace place;
                       Request request = Request
                               .newStatusUpdateRequest(Session.getActiveSession(), "daydaydayday",new Request.Callback() {
                                   @Override
                                   public void onCompleted(Response response) {
                                  Log.d("phanbom","respone ::::"+response.toString());
                                       //showPublishResult(message, response.getGraphObject(), response.getError());
                                   }
                               });
                       request.executeAsync();
                       
 }
        
}
});
}
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

Thứ Năm, 12 tháng 12, 2013

Sự khác nhau giữa Service và IntentService

Service is a base class of service implementation. However, according to my understanding, it's not a best choice to begin with. Service class is run in the application's main thread which may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is borned to make things easier. In my opinion, the main concern of IntentService class is about the thread, but there are also other differences out there.
Differences
  1. Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service.
  2. IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly.
  3. Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when there is no intent in queue. 
  4. IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
  5. IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().
In brief, there are only two things to do to use IntentService. Firstly, to implement the constructor. And secondly, to implement onHandleIntent(). For other callback methods, the super is needed to be called so that it can be tracked properly.

Thứ Hai, 25 tháng 11, 2013

Dùng google translate để dịch trong android

package com.example.studyenglish;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;







/**
 *
 * @author Code4LifeVn
 */
public class TestTranslate {
   
    private final String googleTranslatorURL = "http://translate.google.com/translate_a/t?";
    private LANGUAGE srcLang = LANGUAGE.AUTO;
    private LANGUAGE destLang = LANGUAGE.VIETNAMESE;
    private String userAgent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";

    public String translate(String query) throws MalformedURLException, IOException, ParseException {
        URL url = new URL(this.buildURLRequestWith(query));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("User-Agent", this.userAgent);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(30000);
        conn.connect();

        InputStream inputStream = conn.getInputStream();
        BufferedReader bis = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String respContent = bis.readLine();
        inputStream.close();
        bis.close();
        conn.disconnect();

        StringBuilder contentBuilder = new StringBuilder();

        try {
        JSONObject jsonData = new JSONObject(respContent);
        JSONArray sentences = (JSONArray) jsonData.get("sentences");
   JSONObject jsondetail = sentences.getJSONObject(0);
   contentBuilder.append(jsondetail.get("trans"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

        return contentBuilder.toString().trim().replace(" .", ". ");
    }

    private String buildURLRequestWith(String query) {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(this.googleTranslatorURL);
        urlBuilder.append("client=webapp");
        urlBuilder.append("&sl=auto");
        urlBuilder.append("&tl=").append(this.destLang);
        urlBuilder.append("&hl=").append(this.srcLang);
        urlBuilder.append("&sc=1");
        String queryEncoded = "";
        try {
            queryEncoded = URLEncoder.encode(query, "UTF-8");
            System.out.print(queryEncoded);
        } catch (Exception e) {
        }
        urlBuilder.append("&q=").append(queryEncoded);
        return urlBuilder.toString();
    }

    public LANGUAGE getSrcLang() {
        return srcLang;
    }

    public void setSrcLang(LANGUAGE srcLang) {
        this.srcLang = srcLang;
    }

    public LANGUAGE getDestLang() {
        return destLang;
    }

    public void setDestLang(LANGUAGE destLang) {
        this.destLang = destLang;
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }
   
    public static enum LANGUAGE {
        ENGLISH("en"),
        VIETNAMESE("vi"),
        AUTO("auto");
       
        private String lang = "";
        private LANGUAGE(String lang) {
            this.lang = lang;
        }
        @Override
        public String toString() {
            return this.lang;
        }
    }
       
}

Cách dùng:
TestTranslate translator = new TestTranslate();
       translator.setSrcLang(LANGUAGE.ENGLISH);
       translator.setDestLang(LANGUAGE.VIETNAMESE);
       String data = null;      
try {
data = translator.translate(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (org.apache.http.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Thứ Bảy, 23 tháng 11, 2013

How to copy files in 'assets' to sdcard?

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for(String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
          in.close();
          in = null;
          out.flush();
          out.close();
          out = null;
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }       
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}
Reference : Move file using Java

Thứ Sáu, 22 tháng 11, 2013

Play audio file from the assets directory

public void playBeep() {
    try {

        if (m.isPlaying()) {
            m.stop();
            m.release();
            m = new MediaPlayer();
        }
        AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
        m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        m.prepare();
        m.setVolume(1f, 1f);
        m.setLooping(true);
        m.start();
    } catch (Exception e) {
    }
Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

Thứ Hai, 18 tháng 11, 2013

Listen Scroll in webview

package com.example.studyenglish;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

public class ObservableWebView extends WebView
{
    private OnScrollChangedCallback mOnScrollChangedCallback;

    public ObservableWebView(final Context context)
    {
        super(context);
    }

    public ObservableWebView(final Context context, final AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ObservableWebView(final Context context, final AttributeSet attrs, final int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt)
    {
        super.onScrollChanged(l, t, oldl, oldt);
        if(mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t);
    }

    public OnScrollChangedCallback getOnScrollChangedCallback()
    {
        return mOnScrollChangedCallback;
    }

    public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback)
    {
        mOnScrollChangedCallback = onScrollChangedCallback;
    }

    /**
     * Impliment in the activity/fragment/view that you want to listen to the webview
     */
    public static interface OnScrollChangedCallback
    {
        public void onScroll(int l, int t);
    }
}


wv = (ObservableWebView) findViewById(R.id.scorllableWebview); wv.setOnScrollChangedCallback(new OnScrollChangedCallback(){ public void onScroll(int l, int t){ //Do stuff Log.d(TAG,"We Scrolled etc..."); } });