Friday, 27 December 2013

Google Cloud Messaging(GCM) in Android

Follow the Below Steps
-------------------------

Create a Google API Project
------------------------------
  • Open the Google Cloud Console.
  • If you haven't created an API project yet, click Create Project.
  • Add project name and click Create.
  • Once the project has been created, a page appears that displays your project ID and project number. 
  • Copy your project number, this is your GCM sendeIdnumber
Make the GCM Services Enable
-----------------------------------
 goes  Services and turn the Google Cloud Messaging for Android toggle to ON

Generate API Key
--------------------
goes to API Access
click new Android key, then window will be opened, enter your SHA1 key along with your project package name then click on create button
you will get an api key, copy this key and use it in later

MainActivity.java
-------------------
public class MainActivityextends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

 if (isNetworkAvailable()) {
  if(GCMMessaging.getRegistrationId(MainActivity.this).equals("n/a"))
                        {
                         GCMMessaging.requestRegistration(SplashSceen.this);
                        }

}
else{
Toast.makeText(getApplicationContext(),"No network connection ",3000).show();
}

}

private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}
 

}

 MyIntentService
-------------------
public class MyIntentService extends IntentService {
    @SuppressWarnings("unused")
    private String senderId = Constants.senderId;
    private static int NOTIFICATION_ID = 1;
    private static PowerManager.WakeLock sWakeLock;
    static String TAG = "MyIntentService";

    public MyIntentService() {
        super("MyService");
        // TODO Auto-generated constructor stub
    }
    public MyIntentService(String senderId) {
        // senderId is used as base name for threads, etc.
        super(senderId);
        this.senderId = senderId;
    }
    private static final Object LOCK = MyIntentService.class;

    static void runIntentInService(Context context, Intent intent) {
        synchronized (LOCK) {
            Log.v(TAG, "runIntentInService1");
            if (sWakeLock == null) {
                PowerManager pm = (PowerManager) context
                        .getSystemService(Context.POWER_SERVICE);
                sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                        "my_wakelock");
            }
        }
        sWakeLock.acquire();
        intent.setClassName(context, MyIntentService.class.getName());
        context.startService(intent);
        Log.v(TAG, "runIntentInService finish");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        try {
            String action = intent.getAction();
            Log.v(TAG, "onHandleIntent" + action);
            if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
                Log.v(TAG, "REGISTRATION");
                handleRegistration(MyIntentService.this, intent);

            } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
                handleMessage(MyIntentService.this, intent);
                Log.v(TAG, "RECEIVE MESSAGE");
            } else if (action.equals("com.google.android.c2dm.intent.RETRY")) {
                GCMMessaging.requestRegistration(MyIntentService.this);
                Log.v(TAG, "RETRY");
            }
        } finally {
            synchronized (LOCK) {
                sWakeLock.release();
            }
        }
    }
    private void handleRegistration(Context context, Intent intent) {
        String registration = intent.getStringExtra("registration_id");

        if (intent.getStringExtra("error") != null) {
            // Registration failed, should try again later.
            Log.d("GCM", "registration failed");

            String error = intent.getStringExtra("error");

            if (error == "SERVICE_NOT_AVAILABLE") {
                Log.d("GCM", "SERVICE_NOT_AVAILABLE");
            } else if (error == "ACCOUNT_MISSING") {
                Log.d("GCM", "ACCOUNT_MISSING");
            } else if (error == "AUTHENTICATION_FAILED") {
                Log.d("GCM", "AUTHENTICATION_FAILED");
            } else if (error == "TOO_MANY_REGISTRATIONS") {
                Log.d("GCM", "TOO_MANY_REGISTRATIONS");
            } else if (error == "INVALID_SENDER") {
                Log.d("GCM", "INVALID_SENDER");
            } else if (error == "PHONE_REGISTRATION_ERROR") {
                Log.d("GCM", "PHONE_REGISTRATION_ERROR");
            } else {
                Log.d("GCM", "REGISTRATION_ERROR");
            }
            Editor editor = context.getSharedPreferences(Constants.KEY,
                    Context.MODE_PRIVATE).edit();
            editor.putString(Constants.REGISTRATION_KEY, "n/a");
            editor.putString(Constants.ERROR_DESC, error);
            editor.commit();
        } else if (intent.getStringExtra("unregistered") != null) {
            // unregistration done, new messages from the authorized sender will
            // be rejected
            Log.d("GCM", "unregistered");
            unregisterWithServer(context);
        } else if (registration != null) {
            Log.d("GCM registration ! null", registration);
             saveRegistrationId(context, registration);
            sendRegistrationIdToServer(registration);
                   }
    }
    private void handleMessage(Context context, Intent intent) {
        Log.v("############GCM############", "Received message");
        Intent intent1;
        // String message = intent.getStringExtra("data");
        // String s=message.toString();
        String data = intent.getExtras().getString("message");
        String type = intent.getStringExtra("type");

Intent intent =new Intent();
          Log.v("############GCM##############", "dmControl: message = " + data);
        // TODO Send this to my application server to get the real data
        // Lets make something visible to show that we received the message
        createNotification(context, data, type,intent);
    }
    private void saveRegistrationId(Context context, String registrationId) {
        Log.v("GCM saveregistration id", registrationId);
        Editor editor = context.getSharedPreferences(Constants.KEY,
                Context.MODE_PRIVATE).edit();
        editor.putString(Constants.REGISTRATION_KEY, registrationId);
        editor.putString(Constants.ERROR_DESC, "null");
        editor.commit();
    }
    // public void sendRegistrationIdToServer(String deviceId,String
    // registrationId)
    public void sendRegistrationIdToServer(String registrationId) {
        Log.v("GCM", "Sending registration ID to my application server");

// write code for your webservice
       }
    @SuppressWarnings("deprecation")
    public void createNotification(Context context, String data, String type,Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Title" + data, System.currentTimeMillis());
        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
         PendingIntent pendingIntent = PendingIntent.getActivity(context,
         NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            notification.setLatestEventInfo(context, "title", "" + data,
                pendingIntent);
        notificationManager.notify(NOTIFICATION_ID++, notification);
    }
    private void unregisterWithServer(Context context) {
        // TODO Auto-generated method stub
        }
}


GCMMessaging
------------------
public class GCMMessaging {
        private static final long DEFAULT_BACKOFF = 30000;
    public static final String BACKOFF = "backoff";
    static final String PREFERENCE = "exp_back_off";
    static String tag = "Messaging class";
        static long getBackoff(Context context) {
        final SharedPreferences prefs = context.getSharedPreferences(
                PREFERENCE,
                Context.MODE_PRIVATE);
        return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
    }
       static void setBackoff(Context context, long backoff) {
        final SharedPreferences prefs = context.getSharedPreferences(
                PREFERENCE,
                Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putLong(BACKOFF, backoff);
        editor.commit();
    }
        public static void requestRegistration(Context context) {
        // TODO Auto-generated method stub
                Log.v(tag, "requestRegistrationId method called sender id");
                Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
        intent.putExtra("app",
               PendingIntent.getBroadcast(context, 0, new Intent(), 0));
        // Sender id - project ID generated when signing up
        intent.putExtra("sender", Constants.senderId);                             
        context.startService(intent);
    }
        public static String getRegistrationId(Context context) {
           SharedPreferences prefs = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
             String registraionId = prefs.getString(Constants.REGISTRATION_KEY, "n/a");
             return registraionId;
    }
    public static void removeRegistrationId(Context context) {
            SharedPreferences settings = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = settings.edit();
        edit.putString(Constants.REGISTRATION_KEY, "n/a"); // registration id
        edit.commit(); //apply
        }
}

GCMReceiver
-----------------
public class GCMReceiver extends BroadcastReceiver
{
    Context context;
    String TAG = "GCM receiver";
        @Override
    public void onReceive(Context context, Intent intent) {
                Log.v(TAG, "Registration Receiver called");
        Log.v("#############"+TAG+"###############", "Receiver: "+intent.getAction());
        this.context = context;
                MyIntentService.runIntentInService(context, intent);
        setResult(Activity.RESULT_OK, null, null);
            }
    }

Constants.java
------------------

public class Constants
{

    public static String senderId="enter your project id";
    public static String KEY = "enter your key";
    public static String REGISTRATION_KEY = "n/a";
    public static String ERROR_DESC = "errorDesc";*/
     }
   
   write permissions in manifest file

-----------------------------------
    <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- Creates a custom permission so only this app can receive its messages. -->
    <permission
        android:name="packagename.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="packagename.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />


copy services
----------------
         <receiver
            android:name="packageName.GCMReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
-             <!-- Receive the actual message -->
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="packageName" />
            </intent-filter>
-             <!-- Receive the registration id -->
-             <intent-filter>
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="packageName" />
            </intent-filter>
        </receiver>
        <service android:name="packageName.MyIntentService" />
        

Server side Code
-------------------
write code for sending message,device token and api key  to GCMServer from your server












Wednesday, 25 December 2013

Find Foreground Activity

Finding the Foreground Activity
----------------------------------------

if you want to which activity is running in the foreground
write this code

ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
 List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);               
           
taskInfo.get(0).topActivity.getClassName();   

and add below permission in your manifest file


  <uses-permission android:name="android.permission.GET_TASKS" />   

Saturday, 21 December 2013

Twitter Integration in Android

Steps for Twitter Integration
------------------------------

1. You have to create an Account on Twitter before you do anything.
2. Register you application with Twitter here (https://dev.twitter.com/user)
3. Create new application in twitter
  Name:your project name
  Description:
  website:"enter website"
  Callack url="enter url"


  then, goes to twitter settings in that application type select Access permission and check the Sign in with twitter button copy the consumer key and secret key

 4. open eclipse and create new project
5. write below permissions in manifest file
  <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 then Download below Library files and add to your project 

 signpost-commonshttp4-1.2.1.1.jar
signpost-core-1.2.1.1.jar


http://code.google.com/p/oauth-signpost/

httpclient-4.0.1.jar
http://hc.apache.org/httpcomponents-client-ga/

twitter4j-core-2.1.11
http://twitter4j.org/en/index.html
 
  MainActivity
---------------
 public class MainActivity extends Activity {
    Button buttonLogin;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!OSUtil.IsNetworkAvailable(getApplicationContext())) {
            AlertMessageBox.Show(MainActivity.this, "Internet connection", "A valid internet connection can't be established", AlertMessageBox.AlertMessageBoxIcon.Info);
            return;
        }
              initializeComponent();
    }
    private void initializeComponent() {
        buttonLogin = (Button) findViewById(R.id.buttonLogin);
        buttonLogin.setOnClickListener(buttonLoginOnClickListener);

         }
    private View.OnClickListener buttonLoginOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
 Twitt_Sharing twitt = new Twitt_Sharing(NewsDetails.this,"consumer_key", "secret_key");
       
  twitt.shareToTwitter(your message);
        
        }
    };

    }
 

  TwitterSharing
----------------

public class Twitt_Sharing
{
    InputStream in;
    private final Twitter_Handler mTwitter;
    private final Activity activity;
    private String twitt_msg;
    private String image_path;
    public Twitt_Sharing(Activity act, String consumer_key,String consumer_secret)
    {
        this.activity = act;
        mTwitter = new Twitter_Handler(activity, consumer_key, consumer_secret);
    }
    public void shareToTwitter(String msg)
    {
        this.twitt_msg = msg;
        mTwitter.setListener(mTwLoginDialogListener);

    if (mTwitter.hasAccessToken())
    {
        // this will post data in asyn background thread
       showTwittDialog();
    } else {
        mTwitter.authorize();
            }
    }
    private void showTwittDialog()
    {
        new PostTwittTask().execute(twitt_msg);
    }
    private final TwDialogListener mTwLoginDialogListener = new TwDialogListener()
    {
        @Override
        public void onError(String value)
        {
            showToast("Login Failed");
            mTwitter.resetAccessToken();
        }
        @Override
        public void onComplete(String value)
        {
            showTwittDialog();
        }
    };
    void showToast(final String msg)
    {
        activity.runOnUiThread(new Runnable()
        {
        @Override
        public void run() {
        Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
        }
    });
    }
     class PostTwittTask extends AsyncTask<String, Void, String> {
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute()
    {
        Log.v("in preexecute method","OnPreexecute method in twitter_sharing file");
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Posting Twitt...");
        pDialog.setCancelable(false);
        pDialog.show();
                super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... twitt)
    {
        try
        {
                 activity.runOnUiThread(new Runnable()
            {
                                @Override
                public void run()
                {
                                        try {
                        Share_Pic_Text_Titter(twitt_msg,mTwitter.twitterObj);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
                return "success";
        }
        catch (Exception e)
        {
            if (e.getMessage().toString().contains("duplicate"))
            {
                return "Posting Failed because of Duplicate message...";
            }
            e.printStackTrace();
            return "Posting Failed!!!";
        }
    }
    @Override
    protected void onPostExecute(String result) {
        pDialog.dismiss();
        if (null != result && result.equals("success"))
        {
            showToast("Posted Successfully");
                    }
        else
        {
            showToast(result);
        }
        super.onPostExecute(result);
    }
    }

    public void Share_Pic_Text_Titter(String message,Twitter twitter) throws Exception
    {
    try
    {
        StatusUpdate st = new StatusUpdate(message);

// if you want to post image also then use st.setMedia(image_path);
                twitter.updateStatus(st);
          }
    catch (TwitterException e)
    {
        Log.d("TAG", "Pic Upload error" + e.getErrorMessage());
        Toast.makeText(activity,
            "Ooopss..!!! Failed to update on Twitter.",
            Toast.LENGTH_SHORT).show();
        throw e;
    }
    }
    public void Authorize_UserDetail() {
    }
    class async extends AsyncTask<Void,Void,Void>
    {
        ProgressDialog pDialog;
        @Override
        protected void onPreExecute()
        {
            pDialog = new ProgressDialog(activity);
            pDialog.setMessage("Posting Twitt...");
            pDialog.setCancelable(false);
            pDialog.show();
                        super.onPreExecute();
        }
       @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            mTwitter.setListener(mTwLoginDialogListener);
            return null;
        }
        @Override
        protected void onPostExecute(Void result)
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pDialog.dismiss();
        }
      
    }
}


 Twitter_Handler
------------------
 public class Twitter_Handler {
    public static Twitter twitterObj;
    private final TwitterSession mSession;
    private AccessToken mAccessToken;
    private final CommonsHttpOAuthConsumer mHttpOauthConsumer;
    private final OAuthProvider mHttpOauthprovider;
    private final String mConsumerKey;
    private final String mSecretKey;
    private final ProgressDialog mProgressDlg;
    private TwDialogListener mListener;
    private final Activity context;

    public static final String CALLBACK_URL = "twitterapp://connect";
    private static final String TWITTER_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
    private static final String TWITTER_AUTHORZE_URL = "https://api.twitter.com/oauth/authorize";
    private static final String TWITTER_REQUEST_URL = "https://api.twitter.com/oauth/request_token";

    public Twitter_Handler(Activity context, String consumerKey,
        String secretKey) {
    this.context = context;
    twitterObj = new TwitterFactory().getInstance();
    mSession = new TwitterSession(context);
    mProgressDlg = new ProgressDialog(context);
    mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mConsumerKey = consumerKey;
    mSecretKey = secretKey;
    mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey,
        mSecretKey);
    String request_url = TWITTER_REQUEST_URL;
    String access_token_url = TWITTER_ACCESS_TOKEN_URL;
    String authorize_url = TWITTER_AUTHORZE_URL;
    mHttpOauthprovider = new DefaultOAuthProvider(request_url,
        access_token_url, authorize_url);
    mAccessToken = mSession.getAccessToken();
    configureToken();
    }
    public void setListener(TwDialogListener listener) {
    mListener = listener;
    }
    private void configureToken() {
    if (mAccessToken != null) {
        twitterObj.setOAuthConsumer(mConsumerKey, mSecretKey);
        twitterObj.setOAuthAccessToken(mAccessToken);
    }
    }
    public boolean hasAccessToken() {
    return (mAccessToken == null) ? false : true;
    }
    public void resetAccessToken() {
    if (mAccessToken != null) {
        mSession.resetAccessToken();
        mAccessToken = null;
    }
    }
    public String getUsername() {
    return mSession.getUsername();
    }
    public void updateStatus(String status) throws Exception {
    try {
        twitterObj.updateStatus(status);
    } catch (TwitterException e) {
        throw e;
    }
    }
    public void authorize() {
    mProgressDlg.setMessage("Loading ...");
    mProgressDlg.show();
    new Thread() {
        @Override
        public void run() {
        String authUrl = "";
        int what = 1;
        try {
            authUrl = mHttpOauthprovider.retrieveRequestToken(
                mHttpOauthConsumer, CALLBACK_URL);
            what = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        mHandler.sendMessage(mHandler
            .obtainMessage(what, 1, 0, authUrl));
        }
    }.start();
    }
    public void processToken(String callbackUrl) {
    mProgressDlg.setMessage("Finalizing ...");
    mProgressDlg.show();
    final String verifier = getVerifier(callbackUrl);
    new Thread() {
        @Override
        public void run() {
        int what = 1;
        try {
            mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
                verifier);
            mAccessToken = new AccessToken(
                mHttpOauthConsumer.getToken(),
                mHttpOauthConsumer.getTokenSecret());
            configureToken();
            User user = twitterObj.verifyCredentials();
            mSession.storeAccessToken(mAccessToken, user.getName());
            what = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
        }
    }.start();
    }
    private String getVerifier(String callbackUrl) {
    String verifier = "";
    try {
        callbackUrl = callbackUrl.replace("twitterapp", "http");
        URL url = new URL(callbackUrl);
        String query = url.getQuery();
        String array[] = query.split("&");
        for (String parameter : array) {
        String v[] = parameter.split("=");
        if (URLDecoder.decode(v[0]).equals(
            oauth.signpost.OAuth.OAUTH_VERIFIER)) {
            verifier = URLDecoder.decode(v[1]);
            break;
        }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return verifier;
    }
    private void showLoginDialog(String url) {
    final TwDialogListener listener = new TwDialogListener() {
        @Override
        public void onComplete(String value) {
        processToken(value);
        }
        @Override
        public void onError(String value) {
        mListener.onError("Failed opening authorization page");
        }
    };
    new TwitterDialog(context, url, listener).show();
    }
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        mProgressDlg.dismiss();
        if (msg.what == 1) {
        if (msg.arg1 == 1)
            mListener.onError("Error getting request token");
        else
            mListener.onError("Error getting access token");
        } else {
        if (msg.arg1 == 1)
            showLoginDialog((String) msg.obj);
        else
            mListener.onComplete("");
        }
    }
    };
    public interface TwDialogListener {
    public void onComplete(String value);
    public void onError(String value);
    }
}

TwitterDialog
------------------
public class TwitterDialog extends Dialog {
    static final float[] DIMENSIONS_LANDSCAPE = { 460, 260 };
    static final float[] DIMENSIONS_PORTRAIT = { 280, 420 };
    static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT,
        ViewGroup.LayoutParams.FILL_PARENT);
    static final int MARGIN = 4;
    static final int PADDING = 2;
    private final String mUrl;
    private final TwDialogListener mListener;
    private ProgressDialog mSpinner;
    private WebView mWebView;
    private LinearLayout mContent;
    private TextView mTitle;
    private boolean progressDialogRunning = false;
    public TwitterDialog(Context context, String url, TwDialogListener listener) {
    super(context);
    mUrl = url;
    mListener = listener;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSpinner = new ProgressDialog(getContext());
    mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mSpinner.setMessage("Loading...");
    mContent = new LinearLayout(getContext());
    mContent.setOrientation(LinearLayout.VERTICAL);
    setUpTitle();
    setUpWebView();
    Display display = getWindow().getWindowManager().getDefaultDisplay();
    final float scale = getContext().getResources().getDisplayMetrics().density;
    float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT
        : DIMENSIONS_LANDSCAPE;
    addContentView(mContent, new FrameLayout.LayoutParams(
        (int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
            * scale + 0.5f)));
    }

    private void setUpTitle() {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    mTitle = new TextView(getContext());
    mTitle.setText("Twitter");
    mTitle.setTextColor(Color.WHITE);
    mTitle.setTypeface(Typeface.DEFAULT_BOLD);
    mTitle.setBackgroundColor(0xFFbbd7e9);
    mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
    mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
    //mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
    mContent.addView(mTitle);
    }
    @SuppressLint("SetJavaScriptEnabled")
    private void setUpWebView() {
    mWebView = new WebView(getContext());
    mWebView.setVerticalScrollBarEnabled(false);
    mWebView.setHorizontalScrollBarEnabled(false);
    mWebView.setWebViewClient(new TwitterWebViewClient());
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl(mUrl);
    mWebView.setLayoutParams(FILL);
    mContent.addView(mWebView);
    }
    private class TwitterWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith(Twitter_Handler.CALLBACK_URL)) {
        mListener.onComplete(url);
        TwitterDialog.this.dismiss();
        return true;
        } else if (url.startsWith("authorize")) {
        return false;
        }
        return true;
    }
    @Override
    public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        mListener.onError(description);
        TwitterDialog.this.dismiss();
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        mSpinner.show();
        progressDialogRunning = true;
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        String title = mWebView.getTitle();
        if (title != null && title.length() > 0) {
        mTitle.setText(title);
        }
        progressDialogRunning = false;
        mSpinner.dismiss();
    }
    }
    @Override
    protected void onStop() {
    progressDialogRunning = false;
    super.onStop();
    }
    @Override
    public void onBackPressed() {
    if (!progressDialogRunning) {
        TwitterDialog.this.dismiss();
    }
    }
}



TwitterSession
-----------------
public class TwitterSession {
    private final SharedPreferences sharedPref;
    private final Editor editor;

    private static final String TWEET_AUTH_KEY = "auth_key";
    private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
    private static final String TWEET_USER_NAME = "user_name";
    private static final String SHARED = "Twitter_Preferences";

    public TwitterSession(Context context)
    {
        sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
        editor = sharedPref.edit();
    }
    public void storeAccessToken(AccessToken accessToken, String username)
    {
        editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
        editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
        editor.putString(TWEET_USER_NAME, username);
        editor.commit();
    }
    public void resetAccessToken()
    {
        editor.putString(TWEET_AUTH_KEY, null);
        editor.putString(TWEET_AUTH_SECRET_KEY, null);
        editor.putString(TWEET_USER_NAME, null);
   
        editor.commit();
    }
    public String getUsername()
    {
        return sharedPref.getString(TWEET_USER_NAME, "");
    }
    public AccessToken getAccessToken()
    {
        String token = sharedPref.getString(TWEET_AUTH_KEY, null);
        String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
        if (token != null && tokenSecret != null)
            return new AccessToken(token, tokenSecret);
        else
            return null;
    }
    public void clearsession()
    {
        editor.clear();
        editor.commit();
    }
    public void logoutFromTwitter()
    {
        // Clear the shared preferences
        Editor e = sharedPref.edit();
        e.remove(TWEET_AUTH_KEY);
        e.remove(TWEET_AUTH_SECRET_KEY);
        e.remove(TWEET_USER_NAME);
        e.commit();
          
    }
}


















Sunday, 15 December 2013

NetworkOnMainThreadException

Why we get NetworkOnMainThreadException?

This exception is found in your logcat, when you  read the data through network in main thread
The long process data reading is not run in your main thread
To solve this problem, having following ways:

1)Strictmode:
------------
write this code in your oncreate method

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll()
.build();

StrictMode.setThreadPolicy(policy); 
 
2)AsynkTask
-------------------
write your code inside doInBackground() method

 private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
     protected Long doInBackground(URL... urls) {
         
// write your code here
         return ;
     } 
};


3)Using Thread 
----------------
 
 Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 


Saturday, 14 December 2013

Facebook Integration in Android

Do you know How to integrate facebook into your android application?
First download the facebook sdk from above link and import into your workspace

Create your application and follow these:


manifest.xml
---------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="you package name"
    android:versionCode="1"
    android:versionName="1.0">
   
    <application android:icon="@drawable/icon" android:label="@string/app_name">
   
        <activity android:name=".TestConnect"
                  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=".TestPost"
                  android:label="@string/app_name">
             <intent-filter>
                <action android:name="android.intent.action.VIEW"/>       
            </intent-filter>
        </activity>
     
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-sdk android:minSdkVersion="8" />
  
</manifest>


res/layout/main.xml
----------------------
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="13sp"
        android:textColor="#fff"
        android:text="This example shows how to connect to Facebook, display authorization dialog and save user's token and username"/>
       
    <CheckBox
        android:id="@+id/cb_facebook"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"
        android:text="  Facebook (Not connected) "
        android:textSize="14sp"
        android:textStyle="bold"
        android:textColor="#ccc"
        android:clickable="true"
        android:focusable="true"
        android:button="@drawable/btn_check_facebook"/>
   
    <Button
        android:id="@+id/button1"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" Test Post" />

</LinearLayout>

res/layout/post.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textSize="13sp"
        android:textColor="#fff"
        android:text="This example shows how to post Facebook status"/>
       
    <EditText
        android:id="@+id/revieew"
        android:layout_marginTop="15dp"
        android:layout_width="250dp"
        android:layout_height="100dp"
        android:hint="Write your review"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textSize="13sp"
        android:textColor="#fff"
        android:text="Also share to:"/>
       
    <CheckBox
        android:id="@+id/cb_facebook"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"
        android:text="  Facebook"
        android:textSize="14sp"
        android:clickable="true"
        android:focusable="true"
        android:button="@drawable/btn_check_facebook"/>

    <Button
        android:id="@+id/button1"
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="    Submit    "/>
</LinearLayout>

TestConnection.java
----------------------
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager.Request;
import android.app.ProgressDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.Util;

public class TestConnect extends Activity {
    private Facebook mFacebook;
    private CheckBox mFacebookBtn;
    private ProgressDialog mProgress;
   
    private static final String[] PERMISSIONS = new String[] {"publish_stream", "read_stream", "offline_access"};
   
    private static final String APP_ID = "your facebook app id from fecebook developers";
    protected static final String TOKEN = null;
    private BaseAdapter adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.main);
        generateFBKeyHash();
        mFacebookBtn    = (CheckBox) findViewById(R.id.cb_facebook);
       
        mProgress        = new ProgressDialog(this);
        mFacebook        = new Facebook(APP_ID);
       
        SessionStore.restore(mFacebook, this);
       
        if (mFacebook.isSessionValid()) {
            mFacebookBtn.setChecked(true);
           
            String name = SessionStore.getName(this);
            name        = (name.equals("")) ? "Unknown" : name;
           
            mFacebookBtn.setText("  Facebook (" + name + ")");
            mFacebookBtn.setTextColor(Color.WHITE);
        }
       
        mFacebookBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onFacebookClick();
            }
        });
       
        ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getFriendList();
            
                   
                startActivity(new Intent(TestConnect.this, TestPost.class));
            }
        });
    }
   
    private void onFacebookClick() {
        if (mFacebook.isSessionValid()) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
           
            builder.setMessage("Delete current Facebook connection?")
                   .setCancelable(false)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           fbLogout();
                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                           
                            mFacebookBtn.setChecked(true);
                       }
                   });
           
            final AlertDialog alert = builder.create();
           
            alert.show();
        } else {
            mFacebookBtn.setChecked(false);
           
            mFacebook.authorize(this, PERMISSIONS, -1, new FbLoginDialogListener());
        }
    }
   
    private final class FbLoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionStore.save(mFacebook, TestConnect.this);
          
            mFacebookBtn.setText("  Facebook (No Name)");
            mFacebookBtn.setChecked(true);
            mFacebookBtn.setTextColor(Color.WHITE);
           
            getFbName();
        }

        public void onFacebookError(FacebookError error) {
           Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
          
           mFacebookBtn.setChecked(false);
        }
       
        public void onError(DialogError error) {
            Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
           
            mFacebookBtn.setChecked(false);
        }

        public void onCancel() {
            mFacebookBtn.setChecked(false);
        }
    }
   
    private void getFbName() {
        mProgress.setMessage("Finalizing ...");
        mProgress.show();
       
        new Thread() {
            @Override
            public void run() {
                String name = "";
                int what = 1;
               
                try {
                    String me = mFacebook.request("me");
                   
                    JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue();
                    name = jsonObj.getString("name");
                    what = 0;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
               
                mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name));
            }
        }.start();
    }
   
    private void fbLogout() {
        mProgress.setMessage("Disconnecting from Facebook");
        mProgress.show();
           
        new Thread() {
            @Override
            public void run() {
                SessionStore.clear(TestConnect.this);
                      
                int what = 1;
                   
                try {
                    mFacebook.logout(TestConnect.this);
                       
                    what = 0;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                   
                mHandler.sendMessage(mHandler.obtainMessage(what));
            }
        }.start();
    }
   
    private Handler mFbHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
           
            if (msg.what == 0) {
                String username = (String) msg.obj;
                username = (username.equals("")) ? "No Name" : username;
                   
                SessionStore.saveName(username, TestConnect.this);
               
                mFacebookBtn.setText("  Facebook (" + username + ")");
                
                Toast.makeText(TestConnect.this, "Connected to Facebook as " + username, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestConnect.this, "Connected to Facebook", Toast.LENGTH_SHORT).show();
            }
        }
    };
   
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
           
            if (msg.what == 1) {
                Toast.makeText(TestConnect.this, "Facebook logout failed", Toast.LENGTH_SHORT).show();
            } else {
                mFacebookBtn.setChecked(false);
                mFacebookBtn.setText("  Facebook (Not connected)");
                mFacebookBtn.setTextColor(Color.GRAY);
                  
                Toast.makeText(TestConnect.this, "Disconnected from Facebook", Toast.LENGTH_SHORT).show();
            }
        }
    };
    public void generateFBKeyHash()
    {
     try
     {
      PackageInfo info = getPackageManager().getPackageInfo("com.mobulous.desicomicsreader", PackageManager.GET_SIGNATURES);
      for (Signature signature : info.signatures)
      {
       MessageDigest md = MessageDigest.getInstance("SHA");
       md.update(signature.toByteArray());
//       String key =  Base64.encodeToString(md.digest(), Base64.DEFAULT);
       Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
//       userNameEditText.setText(key);
      }
     } catch (NameNotFoundException e) {

     } catch (NoSuchAlgorithmException e) {

     }
    }
    private void getFriendList()
    {       
        Bundle params = new Bundle();
       
       
        params.putString("method", "fql.query");
        params.putString("query", "SELECT name,uid,pic_square FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1=me() )");
       
       
        AsyncFacebookRunner runner = new AsyncFacebookRunner(this.mFacebook);   
       
        runner.request(params, new RequestListener(){
            public void onComplete(String response) {
                // TODO Auto-generated method stub
                try {
                    JSONObject json = Util.parseJson(response);
                   
                    JSONArray array = json.getJSONArray("data");
                    System.out.println(array.length());
                    for(int i=0;i<array.length();i++){

                        JSONObject friend = array.getJSONObject(i);

                        Log.d("uid",friend.getString("uid"));
                        Log.d("name", friend.getString("name"));
                        Log.d("pic_square",friend.getString("pic_square"+"\n"));            
                    }
                    //System.out.println(json.toString());
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FacebookError e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               
            }

            public void onIOException(IOException e) {
                // TODO Auto-generated method stub
               
            }

            public void onFileNotFoundException(FileNotFoundException e) {
                // TODO Auto-generated method stub
               
            }

            public void onMalformedURLException(MalformedURLException e) {
                // TODO Auto-generated method stub
               
            }

            public void onFacebookError(FacebookError e) {
                // TODO Auto-generated method stub
               
            }
        });
    }
}



TestPost.java
----------------

import android.os.Bundle;
import android.os.Handler;

import android.app.Activity;
import android.app.ProgressDialog;

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.SessionStore;


public class TestPost extends Activity{
    private Facebook mFacebook;
    private CheckBox mFacebookCb;
    private ProgressDialog mProgress;
   
    private Handler mRunOnUi = new Handler();
   
    private static final String APP_ID = "your facebook app id from fecebook developers";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.post);
       
        final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
        mFacebookCb                  = (CheckBox) findViewById(R.id.cb_facebook);
       
        mProgress    = new ProgressDialog(this);
       
        mFacebook     = new Facebook(APP_ID);
       
        SessionStore.restore(mFacebook, this);

        if (mFacebook.isSessionValid()) {
            mFacebookCb.setChecked(true);
               
            String name = SessionStore.getName(this);
            name        = (name.equals("")) ? "Unknown" : name;
               
            mFacebookCb.setText("  Facebook  (" + name + ")");
        }
       
        ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String review = reviewEdit.getText().toString();
               
                if (review.equals("")) return;
           
                if (mFacebookCb.isChecked()) postToFacebook(review);
            }
        });
    }
   
    private void postToFacebook(String review) {   
        mProgress.setMessage("Posting ...");
        mProgress.show();
       
        AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
       
        Bundle params = new Bundle();
           
        params.putString("message", review);
        //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());
    }

    private final class WallPostListener extends BaseRequestListener {
        public void onComplete(final String response) {
            mRunOnUi.post(new Runnable() {
                @Override
                public void run() {
                    mProgress.cancel();
                   
                    Toast.makeText(TestPost.this, "Posted to Facebook", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}


res/drawable/btn_check_facebook.xml
-----------------------------------------

<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:state_window_focused="true"
         android:state_enabled="true"
         android:drawable="@drawable/ic_facebook_on" />

     <item
        android:state_checked="true"
        android:state_window_focused="false"
         android:state_enabled="true"
         android:drawable="@drawable/ic_facebook_on" />
        
    <item
        android:state_checked="false"
        android:state_window_focused="true"
         android:state_enabled="true"
         android:drawable="@drawable/ic_facebook_off" />
        
     <item
         android:drawable="@drawable/ic_facebook_off" />
</selector>