public class UriList {
 
private Context mContext;
 
public UriList(Context context) {
// TODO Auto-generated constructor stub
mContext = context;
}
 
/**
* Function that returns the Registration service uri
* registration/index
* @return getRegistrationUri
*/
public String getRegistrationUri(){
  
return mContext.getResources().getString(R.string.serviceUrl)+"registration/index";
}
  
/**
* Function that returns the Login service uri
* loginpage/loginwebservice
* @return getLoginUri
*/
public String getLoginUri(){
  
return mContext.getResources().getString(R.string.serviceUrl)+"loginpage/loginwebservice";
}
   
 
 
 
 
 
             
 
          
 
 
 
 
 
 
private Context mContext;
public UriList(Context context) {
// TODO Auto-generated constructor stub
mContext = context;
}
/**
* Function that returns the Registration service uri
* registration/index
* @return getRegistrationUri
*/
public String getRegistrationUri(){
return mContext.getResources().getString(R.string.serviceUrl)+"registration/index";
}
/**
* Function that returns the Login service uri
* loginpage/loginwebservice
* @return getLoginUri
*/
public String getLoginUri(){
return mContext.getResources().getString(R.string.serviceUrl)+"loginpage/loginwebservice";
}
//----------------------------------------------------------
public interface RequestTypes {
 static int GET = 0;
 static int POST = 1;
}
//--------------------------------
public class ConnectServer extends Thread{
 private String mServerResponse;
 private String mUri;
 private int mRequestType;
 private List<NameValuePair> mNameValuePairs;
 private String mPostdata;
 private Context mContext;
 public ConnectServer(Context context, String uri, int requestType, List<NameValuePair> nameValuePairs) {
  // TODO Auto-generated constructor stub
  mUri = uri;
  mServerResponse = "";
  mRequestType = requestType;
  mNameValuePairs = nameValuePairs;
  mContext = context;
  startThread();
 }
 public ConnectServer(Context context, String uri, int requestType, String postData) {
  // TODO Auto-generated constructor stub
  mUri = uri;
  mServerResponse = "";
  mRequestType = requestType;
  mPostdata = postData;
  mContext = context;
  startThread();
 }
 public ConnectServer(Context context, String uri, int requestType) {
  // TODO Auto-generated constructor stub
  mUri = uri;
  mServerResponse = "";
  mRequestType = requestType;
  mContext = context;
  startThread();
 }
 private void startThread() {
  // TODO Auto-generated method stub
  if(CheckInternet.checkConn(mContext)){
   Log.e("", "net exists");
   start();
  }
  else{
   if(mContext instanceof Activity){
    Utilities.showMessage
    ("Cannot Connect to Server, Check ur Internet connection", (Activity)mContext);
   }
  }
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  super.run();
  int timeoutConnection = 50000;
  int timeoutSocket = 50000; 
  Log.e("", mUri);
  HttpParams params = new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
  HttpConnectionParams.setSoTimeout(params, timeoutSocket);
  HttpClient client = new DefaultHttpClient(params);
  switch (mRequestType) {
   case RequestTypes.GET: try{
             HttpGet get = new HttpGet(mUri);
             HttpResponse response = client.execute(get);
             mServerResponse = EntityUtils.toString(response.getEntity());
           Log.e("", mServerResponse);
          }
           catch (Exception e) {
            // TODO: handle exception
           Utilities.showMessage
          ("Coonection time out", (Activity)mContext);
           e.printStackTrace();
          }
             break;
   case RequestTypes.POST: try{
          HttpPost post = new HttpPost(mUri);
          if(mNameValuePairs != null){
              MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                 for(int index=0; index < mNameValuePairs.size(); index++) {
                     if(mNameValuePairs.get(index).getName().equalsIgnoreCase("file")) {
                         // If the key equals to "image", we use FileBody to transfer the data
                         entity.addPart(mNameValuePairs.get(index).getName(), new FileBody(new File (mNameValuePairs.get(index).getValue())));
                     } else {
                          // Normal string data
                         entity.addPart(mNameValuePairs.get(index).getName(), new StringBody(mNameValuePairs.get(index).getValue()));
                     }
                 }
              post.setEntity(entity);
          }
          else if(mPostdata !=""){
           post.setEntity(new StringEntity(mPostdata));
           post.setHeader("Accept", "application/json");
           post.setHeader("Content-type", "application/json");
          }
          HttpResponse response = client.execute(post);
            mServerResponse = EntityUtils.toString(response.getEntity());
          Log.e("", mServerResponse);
           }
           catch(Exception e){
            e.printStackTrace();
            Utilities.showMessage
            ("Coonection time out", (Activity)mContext);
           }
  }
 }
 /**
  * Function tht returns server response
  * @return a string containing server response
  */
 public String getServerResponse(){
  return mServerResponse;
 }
}
//-------------------------------------------------
public class CheckInternet {
 public static boolean checkConn(Context ctx)
    {
        ConnectivityManager conMgr =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conMgr.getActiveNetworkInfo();
        if (info == null || !info.isConnected() || !info.isAvailable()){
//    Toast.makeText(ctx, "Internet connection is not available.", Toast.LENGTH_LONG).show();
            return false;
        }
         return true;
    }
 /**
  * Function to check whether google play installed or not 
  * @param context
  * @return
  */
 public static String isGooglePlayInstalled(Context context){
  String GooglePlayStorePackageNameOld = "com.google.market";
  String GooglePlayStorePackageNameNew = "com.android.vending";
  PackageManager packageManager = context.getPackageManager();
     List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
     for (PackageInfo packageInfo : packages) {
         if (packageInfo.packageName.equals(GooglePlayStorePackageNameOld)) {
             return GooglePlayStorePackageNameOld; 
         }
         else if(packageInfo.packageName.equals(GooglePlayStorePackageNameNew)) {
             return GooglePlayStorePackageNameNew; 
            }
     }
     return "";
 }
}
//----------------------------------------------
HOW TO USE
@Override
 public Boolean doBackgroundWork(String[] params) {
  // TODO Auto-generated method stub
  super.doBackgroundWork(params);
  boolean result = false;
  ConnectServer server;
  try {
   if(misFbPressed){
    server = new ConnectServer(Login.this, new UriList(
      getBaseContext()).getFacebookLoginUrl(), RequestTypes.POST,
      getNameValuePairs(params));
    while (server.isAlive());
    if (server.getServerResponse().length()>0) {
     GCMRegistrar.setRegisteredOnServer(getBaseContext(), true);
     JSONArray array = (JSONArray) new JSONTokener(
       server.getServerResponse()).nextValue();
     if (array.length() > 0) {
      if(array.getJSONObject(0).getString("public_name").trim().length()>0){
       saveDetailsToPreference(array);
       result = true;
       getSharedPreferences(UserDetailsForPref.PREF_NAME, MODE_PRIVATE)
       .edit().putBoolean(Utilities.isloggedin, true).commit();
      }
      else{
       updateUserDetails(array);
      }
     }
    }
   }
0 comments: