First of all this is my solution for a one of my SE project @ SLIIT.
Here this solution sends the gps cordinaes of the users location in to the server and the server will be abele to capture the signels and show them in the defined page.
Later we can manipulate these data in the server and display them in a separate place. Ex: a dashboard
LocationGPSTrackerActivity class
This class checkes wheter the network is availabale and the gps is working corretly in the device. if not it will
display on screen messages based on the results
public class LocationGPSTrackerActivity extends Activity implements LocationListener {
private final static String CONNECTIVITY = "android.net.conn.CONNECTIVITY_CHANGE";
private LocationManager locationManager;
private ConnectivityManager connectivityManager;
SharedPreferences preferences;
private EditText edit_url;
private TextView text_gps_status;
private TextView text_network_status;
private ToggleButton button_toggle;
private TextView text_running_since;
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(LocationGPSTrackerService.NOTIFICATION)) {
updateServiceStatus();
}
if (action.equals(CONNECTIVITY)) {
updateNetworkStatus();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpstracker);
edit_url = (EditText)findViewById(R.id.edit_url);
text_gps_status = (TextView)findViewById(R.id.text_gps_status);
text_network_status = (TextView)findViewById(R.id.text_network_status);
button_toggle = (ToggleButton)findViewById(R.id.button_toggle);
text_running_since = (TextView)findViewById(R.id.text_running_since);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.contains("URL") && ! preferences.getString("URL", "").equals("")) {
edit_url.setText(preferences.getString("URL", getString(R.string.hint_url)));
edit_url.clearFocus();
} else {
edit_url.requestFocus();
}
edit_url.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("URL", s.toString().trim());
editor.commit();
}
});
registerReceiver(receiver, new IntentFilter(LocationGPSTrackerService.NOTIFICATION));
registerReceiver(receiver, new IntentFilter(LocationGPSTrackerActivity.CONNECTIVITY));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
int pref_gps_updates = Integer.parseInt(preferences.getString("pref_gps_updates", "30"));
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, pref_gps_updates * 1000, 1, this);
}
@Override
public void onResume() {
super.onResume();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
onProviderEnabled(LocationManager.GPS_PROVIDER);
} else {
onProviderDisabled(LocationManager.GPS_PROVIDER);
}
updateNetworkStatus();
updateServiceStatus();
}
private void updateServiceStatus() {
if (LocationGPSTrackerService.isRunning) {
Toast.makeText(this, getString(R.string.toast_service_running), Toast.LENGTH_SHORT).show();
button_toggle.setChecked(true);
text_running_since.setText(getString(R.string.text_running_since) + " "
+ DateFormat.getDateTimeInstance().format(LocationGPSTrackerService.runningSince.getTime()));
} else {
Toast.makeText(this, getString(R.string.toast_service_stopped), Toast.LENGTH_SHORT).show();
button_toggle.setChecked(false);
if (preferences.contains("stoppedOn")) {
long stoppedOn = preferences.getLong("stoppedOn", 0);
if (stoppedOn > 0) {
text_running_since.setText(getString(R.string.text_stopped_on) + " "
+ DateFormat.getDateTimeInstance().format(new Date(stoppedOn)));
} else {
text_running_since.setText(getText(R.string.text_killed));
}
}
}
}
private void updateNetworkStatus() {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
text_network_status.setText(getString(R.string.text_network_status_enabled));
text_network_status.setTextColor(Color.BLACK);
} else {
text_network_status.setText(getString(R.string.text_network_status_disabled));
text_network_status.setTextColor(Color.RED);
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this);
unregisterReceiver(receiver);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menue, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.id.menu_settings:
i = new Intent(this, LocationGPSTrackerPrefs.class);
startActivity(i);
break;
default:
}
return super.onOptionsItemSelected(item);
}
public void onToggleClicked(View view) {
Intent intent = new Intent(this, LocationGPSTrackerService.class);
if (((ToggleButton) view).isChecked()) {
startService(intent);
} else {
stopService(intent);
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
text_gps_status.setText(getString(R.string.text_gps_status_disabled));
text_gps_status.setTextColor(Color.RED);
}
@Override
public void onProviderEnabled(String provider) {
text_gps_status.setText(getString(R.string.text_gps_status_enabled));
text_gps_status.setTextColor(Color.BLACK);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationGPSTrackerService
This class is used to display tracking details on the tracker app and to call the LocationGPSTrackerRequest class to open a Http request to the server
public class LocationGPSTrackerService extends IntentService implements LocationListener {
public static final String NOTIFICATION = "com.example.testmapv2";
public static boolean isRunning;
public static Calendar runningSince;
public Calendar stoppedOn;
private final static String MY_TAG = "LocationGPSTrackerService";
private SharedPreferences preferences;
private String urlText;
private LocationManager locationManager;
private int pref_gps_updates;
private long latestUpdate;
private int pref_max_run_time;
public LocationGPSTrackerService() {
super("LocationGPSTrackerService");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(MY_TAG, "in onCreate, init GPS stuff");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
onProviderEnabled(LocationManager.GPS_PROVIDER);
} else {
onProviderDisabled(LocationManager.GPS_PROVIDER);
}
preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("stoppedOn", 0);
editor.commit();
pref_gps_updates = Integer.parseInt(preferences.getString("pref_gps_updates", "30"));
pref_max_run_time = Integer.parseInt(preferences.getString("pref_max_run_time", "24"));
urlText = preferences.getString("URL", "");
if (urlText.contains("?")) {
urlText = urlText + "&";
} else {
urlText = urlText + "?";
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, pref_gps_updates * 1000, 1, this);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(MY_TAG, "in onHandleIntent, run for maximum time set in preferences");
new LocationGPSTrackerRequest().execute(urlText + "tracker=start");
isRunning = true;
runningSince = Calendar.getInstance();
Intent i = new Intent(NOTIFICATION);
sendBroadcast(i);
Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.toast_service_running), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, LocationGPSTrackerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.app_name), getText(R.string.toast_service_running), pendingIntent);
startForeground(R.id.logo, notification);
}
@Override
public void onDestroy() {
// destroy when user clicked the stop button or maximum run time has been reached
Log.d(MY_TAG, "in onDestroy, stop listening to the GPS");
new LocationGPSTrackerRequest().execute(urlText + "tracker=stop");
locationManager.removeUpdates(this);
isRunning = false;
stoppedOn = Calendar.getInstance();
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("stoppedOn", stoppedOn.getTimeInMillis());
editor.commit();
Intent intent = new Intent(NOTIFICATION);
sendBroadcast(intent);
}
@Override
public void onLocationChanged(Location location) {
Log.d(MY_TAG, "in onLocationChanged, latestUpdate == " + latestUpdate);
if ((System.currentTimeMillis() - latestUpdate) < pref_gps_updates*1000) {
return;
} else {
latestUpdate = System.currentTimeMillis();
}
new LocationGPSTrackerRequest().execute(urlText + "lat=" + location.getLatitude() + "&lon=" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Sending Http request to the server
public class LocationGPSTrackerRequest extends AsyncTask<String, Void, Void> {
private final static String MY_TAG = "LocationGPSTrackerRequest";
protected Void doInBackground(String... urlText) {
try {
URL url = new URL(urlText[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d(MY_TAG, "HTTP request done : " + response);
} catch (Exception e) {
// whrn network down
Log.d(MY_TAG, "HTTP request failed");
}
return null;
}
}
New
How to send GPS cordinates from android app to web server
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment