Thursday 17 October 2013

Get Current location using GPS

package com.mrs.golfapp;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity{
private CommonClass mCommonClass=new CommonClass();
private NotificationManager mNotificationManager=null;
    private Intent mNotificationIntent;
private TextView txtGpsStrength = null;
private TextView txtElapsedTime = null;
public  TextView txtAntal;
private TextView txtRecording;
private Button StartButton=null,PauseButton=null;
private ImageView imgGpsStrength = null;
private LinearLayout lytAntal;
private SharedPreferences mSharedPreferences_Write = null;
private SharedPreferences mSharedPreferences_Read = null;
private final long mFrequency = 100;
    private final int TICK_WHAT = 2;
    private boolean GPS_Recording=false;
    private boolean GPS_Setting_Dialog_Not_Open=true;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.xmain_activity);
        startWakeLock();
       
        mSharedPreferences_Read=getSharedPreferences(Constant.SHAREDPREFERENCE.SHAREDPREFERENCE,MODE_WORLD_READABLE);
        mSharedPreferences_Write=getSharedPreferences(Constant.SHAREDPREFERENCE.SHAREDPREFERENCE,MODE_WORLD_WRITEABLE);
       
        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        mNotificationIntent = new Intent(this, MainActivity.class);
       
        txtGpsStrength = (TextView)findViewById(R.id.txtGpsStrength);
        imgGpsStrength =(ImageView)findViewById(R.id.ImgGpsStrength);

        txtElapsedTime = (TextView)findViewById(R.id.ElapsedTime);
        txtRecording =(TextView)findViewById(R.id.txtRecording);
        txtRecording.setText(getResources().getText(R.string.not_recording));
       
        StartButton = (Button)findViewById(R.id.StartButton);
        PauseButton = (Button)findViewById(R.id.PauseButton);
       
        txtAntal = (TextView)findViewById(R.id.txtAntal);
txtAntal.setText(String.valueOf(mSharedPreferences_Read.getInt(Constant.SHAREDPREFERENCE.NO_OF_PEOPLE, 1)));

        lytAntal = (LinearLayout)findViewById(R.id.lytAntalMensen);
        lytAntal.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Selected_Person=mSharedPreferences_Read.getInt(Constant.SHAREDPREFERENCE.NO_OF_PEOPLE, 1);
AlertDialogSelectPerson();
}
});
       
        startService(new Intent(this, StopwatchService.class));
        bindStopwatchService();
        mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), mFrequency);      
    }

//***********************************************************************************************************************
/**
 * @author Manisha
 * @return
 * @use For update elapsed time
 */
//************************************************************************************************************************
private Handler mHandler = new Handler() {
        public void handleMessage(Message m) {
        updateElapsedTime();
        sendMessageDelayed(Message.obtain(this, TICK_WHAT), mFrequency);
        }
    };
   
//***********************************************************************************************************************
/**
 * @author Manisha
 * @return
 * @use Connection to the backgorund StopwatchService
 */
//************************************************************************************************************************
    private StopwatchService m_StopwatchService=null;
private ServiceConnection m_StopwatchServiceConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
m_StopwatchService = ((StopwatchService.LocalBinder)service).getService();
}

@Override
public void onServiceDisconnected(ComponentName name) {
m_StopwatchService = null;
}
};

private void bindStopwatchService() {
        bindService(new Intent(this, StopwatchService.class),m_StopwatchServiceConn, Context.BIND_AUTO_CREATE);
}

private void unbindStopwatchService() {
if(m_StopwatchService != null ) {
unbindService(m_StopwatchServiceConn);
}
}
   
@Override
public void onDestroy() {
if(m_StopwatchService != null ) {
    m_StopwatchService.reset();
}
         unbindStopwatchService();
         stopService(new Intent(this, StopwatchService.class));
         RemoveLocationManager();
         stopWakeLock();
super.onDestroy();
}

@Override
protected void onRestart() {
super.onRestart();
if(mNotificationManager!=null){
mNotificationManager.cancelAll();
}
}

@Override
protected void onResume() {
    GPS_Setting_Dialog_Not_Open=true;
        getLocation();
super.onResume();
}

@Override
protected void onPause() {
super.onPause();
    if(!isFinishing() && GPS_Setting_Dialog_Not_Open){
    Activity_Minimize();
    }
}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param View
 * @return void
 * @use This code is used when user clik on upload button
 */
//************************************************************************************************************************
    public void onStartClicked(View v) {
    Log.d(Constant.TAG, "start button clicked");
    Start_Sending();
    }
   
    private void Start_Sending(){
if(getGPS_Status()){
    if(m_StopwatchService!=null){
    m_StopwatchService.start();
    }
    txtRecording.setText(getResources().getText(R.string.recordig));
    GPS_Recording=true;
    showPauseButtons();
     }
else{
getLocation();
}
    }
   
   
   
//***********************************************************************************************************************
/**
 * @author Manisha
 * @param View
 * @return void
 * @use This code is used when user clik on pause button
 */
//************************************************************************************************************************
   
    public void onPauseClicked(View v) {
    Log.d(Constant.TAG, "pause button clicked");
    Pause_Sending();
    }
   
    private void Pause_Sending(){
    if(m_StopwatchService!=null){
        m_StopwatchService.pause();
    }
    txtRecording.setText(getResources().getText(R.string.not_recording));
    GPS_Recording=false;
    showStartButton();
    }
   
    public void updateElapsedTime() {
    if(m_StopwatchService != null)
    txtElapsedTime.setText(m_StopwatchService.getFormattedElapsedTime());
    }
   
    private void showPauseButtons() {
    Log.d(Constant.TAG, "showPauseLapButtons");
    StartButton.setVisibility(View.GONE);
    PauseButton.setVisibility(View.VISIBLE);
    }
   
    private void showStartButton() {
    Log.d(Constant.TAG, "showStartResetButtons");
    StartButton.setVisibility(View.VISIBLE);
    PauseButton.setVisibility(View.GONE);
    }
       
//***********************************************************************************************************************
/**
 * @author Manisha
 * @param none
 * @return void
 * @use This method is used for minimize activity
 */
   
//************************************************************************************************************************
    private void Activity_Minimize(){
    Show_Running_Notification();
        Intent mIntent = new Intent(Intent.ACTION_MAIN);      
        mIntent.addCategory(Intent.CATEGORY_HOME);
        startActivity(mIntent);
    }
   
//***********************************************************************************************************************
/**
 * @author Manisha
 * @param none
 * @return void
 * @use This method is used for show notification
 */
//************************************************************************************************************************  
     private void Show_Running_Notification() {
        CharSequence strNotificationTitle = Constant.NOTIFICATION.NOTIFICATIONTITLE;
        Notification notification = new Notification(R.drawable.ic_notification, strNotificationTitle, System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this,0 ,mNotificationIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
        notification.setLatestEventInfo(this, Constant.NOTIFICATION.NOTIFICATIONRUNNINGMESSAGE,Constant.NOTIFICATION.NOTIFICATIONRUNNINGTEXT, contentIntent);
        notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_NO_CLEAR;  
        mNotificationManager.notify(1, notification);
     }
   
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK)
           {  
        Finish_Activity_Alert();
        return true;
        }
        return super.onKeyDown(keyCode, event);
    }
   
//***********************************************************************************************************************
/**
 * @author Manisha
 * @param none
 * @return void
 * @use This code is for show dialog for person selection
 */
   
//************************************************************************************************************************
    int Selected_Person=0;
    private void AlertDialogSelectPerson(){
   final CharSequence[] items = {"Person 0","Person 1","Person 2","Person 3","Person 4","Person 5","Person 6","Person 7","Person 8",
"Person 9","Person 10","Person 11","Person 12","Person 13","Person 14","Person 15","Person 16","Person 17",
"Person 18","Person 19","Person 20","Person 21","Person 22","Person 23","Person 24","Person 25","Person 26",
"Person 27","Person 28","Person 29","Person 30","Person 31","Person 32","Person 33","Person 34","Person 35",
"Person 36","Person 37","Person 38","Person 39","Person 40"
};
       AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle(Constant.SELECTPERSONDIALOG.DIALOGTITLE);
     
       builder.setNegativeButton(Constant.SELECTPERSONDIALOG.BUTTON_CANCEL, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
     
       builder.setPositiveButton(Constant.SELECTPERSONDIALOG.BUTTON_OK, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
txtAntal.setText(String.valueOf(Selected_Person));

SharedPreferences.Editor mEditor  = mSharedPreferences_Write.edit();
mEditor.putInt(Constant.SHAREDPREFERENCE.NO_OF_PEOPLE, Selected_Person);
mEditor.commit();
           }
       });

       builder.setSingleChoiceItems(items, Selected_Person, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int item) {
            Selected_Person=item;
           }
       });
       AlertDialog mAlertDialog = builder.create();
       mAlertDialog.show();
}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param none
 * @return void
 * @use This code is for show dialog for finish activity
 */
//************************************************************************************************************************
private void Finish_Activity_Alert() {
    AlertDialog mAlertDialog = new AlertDialog.Builder(this).create();
    mAlertDialog.setIcon(R.drawable.ic_logo);
    mAlertDialog.setTitle(Constant.FINISHACTIVITYDIALOG.DIALOGTITLE);
       mAlertDialog.setMessage(Constant.FINISHACTIVITYDIALOG.DISCARDMESSAGE);
       mAlertDialog.setCancelable(false);
       mAlertDialog.setButton(Constant.FINISHACTIVITYDIALOG.BUTTON_FINISH, new DialogInterface.OnClickListener() {          
           public void onClick(DialogInterface dialog, int which) {
        finish();
        return;
           }
       });
       mAlertDialog.setButton2(Constant.FINISHACTIVITYDIALOG.BUTTON_CANCEL, new DialogInterface.OnClickListener() {                      
           public void onClick(DialogInterface dialog, int which) {
               dialog.cancel();
               return;
           }
       });
       mAlertDialog.setButton3(Constant.FINISHACTIVITYDIALOG.BUTTON_MINIMIZE, new DialogInterface.OnClickListener() {                      
           public void onClick(DialogInterface dialog, int which) {
            Activity_Minimize();
               dialog.cancel();
               return;
           }
       });
       // Create and show the dialog
       mAlertDialog.show();
}

 //************************************************************************************************************************
 public void Show_GPS_Settings_Alert(){
       AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(this);
       mAlertDialog.setTitle(Constant.GPSSETTING.GPSSETTING_TITLE);
       mAlertDialog.setMessage(Constant.GPSSETTING.GPS_MESSAGE);
       mAlertDialog.setPositiveButton(Constant.GPSSETTING.GPS_POSITIVE_BUTTON, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog,int which) {
            GPS_Setting_Dialog_Not_Open=false;
               Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
               MainActivity.this.startActivity(intent);
               dialog.cancel();
           }
       });
       mAlertDialog.setNegativeButton(Constant.GPSSETTING.GPS_CANCEL_BUTTON, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
           }
       });
       mAlertDialog.show();
 }

  * @use Use the LocationManager class to obtain GPS locations
  */
 //************************************************************************************************************************
 private LocationManager mLocationManager=null;
 private LocationListener mLocationListener =null;
 private void getLocation(){    
        /* Use the LocationManager class to obtain GPS locations */
    if(mLocationManager==null){
  mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  if(getGPS_Status()){
txtGpsStrength.setText(getResources().getString(R.string.gps_locating));
imgGpsStrength.setBackgroundResource(R.drawable.signal_black);
  AddLocationManager();
      }
      else{
       Show_GPS_Settings_Alert();
       mLocationManager=null;
       mLocationListener=null;
      }
    }
 }

 private Boolean getGPS_Status(){
 if(mLocationManager!=null){
  return mLocationManager.isProviderEnabled(Constant.PROVIDER);
 }
 else{
 return false;
 }
 }

 private String getDeviceID(){
return Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
 }
 private void  AddLocationManager() {
if(mLocationManager!=null)
{
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(Constant.PROVIDER,Constant.minTime, Constant.minDistance, mLocationListener);
}
 }

 private void RemoveLocationManager() {
if(mLocationListener!=null && mLocationManager!=null)
{
mLocationManager.removeUpdates(mLocationListener);
mLocationListener=null;
mLocationManager=null;
}
 }

 private class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc){
if(GPS_Recording){
if(mSendLocation == null){
mSendLocation=new SendLocation();
mSendLocation.execute(loc);
}
}

float accuracy = loc.getAccuracy();
if(accuracy > 30){
            txtGpsStrength.setText(Constant.GPSSETTING.GPS_SIGNAL_OK);
            imgGpsStrength.setBackgroundResource(R.drawable.signal_green);
           }
           else if(accuracy > 20 && accuracy < 30){
            txtGpsStrength.setText(Constant.GPSSETTING.GPS_SIGNAL_AVARAGE);
            imgGpsStrength.setBackgroundResource(R.drawable.signal_orange);
           }
           else if(accuracy < 20){
            txtGpsStrength.setText(Constant.GPSSETTING.GPS_SIGNAL_WEAK);
            imgGpsStrength.setBackgroundResource(R.drawable.signal_red);
           }
}
@Override
public void onProviderDisabled(String provider){
txtGpsStrength.setText(getResources().getString(R.string.gps_off));
imgGpsStrength.setBackgroundResource(R.drawable.signal_gray);
Pause_Sending();
}
@Override
public void onProviderEnabled(String provider){
txtGpsStrength.setText(getResources().getString(R.string.gps_locating));
imgGpsStrength.setBackgroundResource(R.drawable.signal_black);
Start_Sending();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
  }

 private SendLocation mSendLocation = null;
 private class SendLocation extends AsyncTask
   {

       protected String doInBackground(Location... location) {
        Log.d(Constant.TAG, "Location Request = " + "doInBackground");
    String strURL=MainActivity.this.getResources().getString(R.string.location_update_url);
    ArrayList alstNameValuePair = new ArrayList();
    alstNameValuePair.add(new BasicNameValuePair(MainActivity.this.getResources().getString(R.string.Action),MainActivity.this.getResources().getString(R.string.Set)));
    alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.DEVICEID,getDeviceID().toString()));
    alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.LATITUDE,String.valueOf(location[0].getLatitude()).toString()));
    alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.LONGITUDE,String.valueOf(location[0].getLongitude()).toString()));
    alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.NO_OF_PEOPLE,String.valueOf(mSharedPreferences_Read.getInt(Constant.SHAREDPREFERENCE.NO_OF_PEOPLE, 1))));
    alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.TIMESTAMP, new SimpleDateFormat(Constant.TIME_STAMP_FORMAT).format(new Date(location[0].getTime()))));
    Log.d(Constant.TAG, "Location Request = " + alstNameValuePair.toString());
    return mCommonClass.PostConnection(strURL, alstNameValuePair);
       }          
     
       protected void onPostExecute(String result) {
       if(result!=null){
        Log.d(Constant.TAG, "Location Response = " + result.toString());
       }
       else{
       }
           super.onPostExecute(result);
           mSendLocation = null;
       }
   }
 
  private WakeLock mWakeLock=null;
private static final String WAKE_LOCK_TAG = "WAKE_LOCK_LOCATION_UPDATE_SERVICE";
private void startWakeLock() {

   if (mWakeLock == null) {
     Log.d(Constant.TAG, "wakeLock is null, getting a new WakeLock");
     PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
     Log.d(Constant.TAG, "PowerManager acquired");
     mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);
     Log.d(Constant.TAG, "WakeLock set");
   }
   mWakeLock.acquire();
   Log.d(Constant.TAG, "WakeLock acquired");
}

private void stopWakeLock() {
   if (mWakeLock != null) {
    mWakeLock.release();
     Log.d(Constant.TAG, "WakeLock released");
   }
}
}

No comments:

Post a Comment