Getting location Updates in Android - android

Hi AM using the code below used here : How to get current location in Android
Here am using the TextView to display the location coordinates once.
Now How can I keep update the location in TextView once the location keeps changing.
Codes i'm using now: This is my main Activity
package com.example.locationtests;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GPSTracker mGPS = new GPSTracker(this);
TextView text = (TextView) findViewById(R.id.texts);
if(mGPS.canGetLocation ){
mGPS.getLocation();
text.setText("Lat"+mGPS.getLatitude()+"Lon"+mGPS.getLongitude());
}else{
text.setText("Unabletofind");
System.out.println("Unable");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is the class im using for Tracking:
package com.example.locationtests;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Function to get the user's current location
*
* #return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
location=null;
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationtests"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.location" android:required="true" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationtests.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

When you call the method requestLocationUpdates on locationManger, you specify 'this' as the LocationListener:
locationManager.requestLocationUpdates(..., ..., ..., this);
That's fine since the class implements LocationListener. The callback made when the location changes is the method 'onLocationChanged'. You have this method in your class but it has no code so does nothing:
#Override
public void onLocationChanged(Location location) {
}
Add appropriate code to get the new Latitude and Longitude from the 'location' parameter and update the TextView back in your Activity. There are a number of ways to do that. Two that come to mind:
1) Pass a reference to the TextView in the GPSTracker class constructor so you can access it from the class.
2) Pass a reference to the Activity in the GPSTracker class constructor so you can call a method in your Activity (that accepts the values to show) that can then update the TextView.
EDIT:
You already have the reference I refer to in point 2 above. When you instantiate your instance of GPSTracker in your Activity, you already pass it 'this':
GPSTracker mGPS = new GPSTracker(this);
In this case 'this' is the instance of your MainActivity class and an Activity class also happens to be a Context. In the constructor of GPSTracker you are storing this context in a variable:
public GPSTracker(Context context) {
this.mContext = context;
You can therefore use it to access the TextView. Cast the context you have to an Activity and you can then use the findViewById method on it:
#Override
public void onLocationChanged(Location location)
{
TextView text = (TextView) ((Activity)mContext).findViewById(R.id.texts);
text.setText("Lat"+location.getLatitude()+"Lon"+location.getLongitude());
}

Do something like this:
Sample code:
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "GPS LocationChanged");
double lat = location.getLatitude();
double lng = location.getLongitude();
Log.d(TAG, "Received GPS request for " + String.valueOf(lat) + "," + String.valueOf(lng) + " , ready to rumble!");
// Do clever stuff here
}

Related

get Latitude Longitude fail

I have two question with my code
can not enter the onLocationChanged() function
mylocation is always null
I also add the permission and turn on my device GPS function
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name ="android.permission.ACCESS_COARSE_LOCATION"/>
follows is my code please help me to get Latitude Lontitude thanks all.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Getaddress getaddress = new Getaddress();
getaddress.excute();
}
public class Getaddress implements LocationListener {
Geocoder geocoder;
private Location mylocation;
private double Latitude;
private double Lontitude;
private LocationManager locationManager;
public Getaddress() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
mylocation = locationManager.getLastKnownLocation(provider);
Boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.w("isGPSEnabled",isGPSEnabled.toString());
}
public void excute()
{
Latitude = mylocation.getLatitude();
Lontitude = mylocation.getLongitude();
Toast.makeText(SecondActivity.this, "Latitude"+Double.toString(Latitude),Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location)
{
mylocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Xml File :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/str_tv_location"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_location"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_longitude"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Java file:
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Permission :-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
At first: you need GPS available space.
Secondly: your location is always null, because your space for GRP LOCATION not available. You need to check if GPS working or not
onLocationChanged method work every time when your location changed.
public class GPSTracker implements LocationListener {
public GPSTracker(Context con){
LocationManager lm = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// do something here...
//location.getLatitude();
//location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Background Service is crashing on "start service"

I have to find the location of user such that , that even when I close the app it continues in the background. The code working fine and it's displaying correct locations but when I click "Start Service" It crashes. I can't find the mistake:
GPS TRACKING CLASS
package com.malay.gpsservice;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class GPSTracService extends Service implements LocationListener {
// DECLARE ALL THE VARIABLES
Location location = null; // location
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled=false;
String msg = "CAUTION! If kept open, can consume lots of battery";
// FOR FOREGROUND_ID
int FORE_ID = 1335;
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("NewApi")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent noty_intent = new Intent(this,
com.malay.gpsservice.MainActivity.class);
noty_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, noty_intent,
0);
Notification n = new Notification.Builder(this)
.setContentTitle("GPS Serice is running...")
.setContentText(msg).setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).setAutoCancel(true).setOngoing(true)
.build();
startForeground(FORE_ID, n);
try {
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// First get location from Network Provider
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network","Network");
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if (!isGPSEnabled) {
} else {
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(this,
"Location Listener on GPS started...",
Toast.LENGTH_SHORT).show();
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception ex) {
Toast.makeText(this,
"Some Error occur while starting Location Listener",
Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
return (START_STICKY);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (locationManager != null) {
locationManager.removeUpdates((LocationListener) this);
locationManager = null;
}
stopForeground(true);
Toast.makeText(this, "Location Listener on GPS Stopped...",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
here is the main activity:
package com.malay.gpsservice;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener{
Context mcontext=this;
boolean isGpsEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
protected LocationManager locManager;
Location loc=null;
double latitude;
double longitude;
double accuracy;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE=20;
private static final long MIN_TIME_BETWEEN_UPDATE=1000*60;
double latitudet;
double longitudet;
double accuracyt;
TextView tview;
TextView tlat;
TextView tlon;
TextView tacc;
String lat;
String lon;
String acc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loc=getLocation();
tview = (TextView) findViewById(R.id.textView1);
try {
getGPSLoc();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
//Refresh Button
if (item.getItemId() == R.id.ref) {
getLocation();
getGPSLoc();
}
return super.onMenuItemSelected(featureId, item);
}
public void getGPSLoc() {
if (latitude != 0.0 && longitude != 0.0) {
tview.setText("Location Fixed");
} else {
tview.setText("Waiting for Location...");
}
if (canGetLocation) {
latitudet=(double)Math.round(latitude*1000000)/1000000;
tlat = (TextView) findViewById(R.id.lat);
lat = Double.toString(latitudet);
tlat.setText(lat);
longitudet=(double)Math.round(longitude*1000000)/1000000;
tlon = (TextView) findViewById(R.id.lon);
lon = Double.toString(longitudet);
tlon.setText(lon);
accuracyt=(double)Math.round(accuracy*100)/100;
tacc = (TextView) findViewById(R.id.acc);
acc = Double.toString(accuracyt);
tacc.setText(acc);
}
}
public Location getLocation(){
try{
locManager=(LocationManager)mcontext.getSystemService(LOCATION_SERVICE);
isGpsEnabled=locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGpsEnabled || isNetworkEnabled){
this.canGetLocation=true;
// First get location from Network Provider
if(isNetworkEnabled){
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, (LocationListener) this);
Log.d("Network","Network");
if(locManager!=null){
loc=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
accuracy=loc.getAccuracy();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if(isGpsEnabled){
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, (LocationListener) this);
Log.d("GPS Enabled","GPS Enabled");
if(locManager!=null){
loc=locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
accuracy=loc.getAccuracy();
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
return loc;
}
public void startServ(View vw){
Intent gps=new Intent(this,GPSTracService.class);
this.startService(gps);
}
public void stopServ(View vw){
Intent gps=new Intent(this,GPSTracService.class);
this.stopService(gps);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.malay.gpsservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.malay.gpsservice.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GPSTracService" />
</application>
</manifest>
Logcat
Use getApplicationContext() instead of this in service.
Changed below line.
Intent noty_intent = new Intent(getApplicationContext(), com.malay.gpsservice.MainActivity.class);
.
.
Notification n = new Notification.Builder(getApplicationContext())
instead of
Intent noty_intent = new Intent(this, com.malay.gpsservice.MainActivity.class);
Note : must declare service in menifest.xml if it missing.
Update :
Use below code for Notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setStyle(new NotificationCompat.BigTextStyle().bigText("App Name"))
.setContentText("App Name");
startForeground(1, mBuilder.build());
Use android.support.v7 library and set Target Version 21

How to use Android LocationManager and Listener

I'm not having any luck receiving any data from the GPS using the code below, and i'm not sure what I'm doing wrong, it seems like my code matches everything i see online. i'd like to eventually add this to a background service to log gps coordinates even when the activity isn't visible or if other apps are open and if the speed is greater than a certain defined amount, but at this point I can't even get any of the data to show up. i'm relatively new to android but i can't figure out what am i doing wrong?
public class MainActivity extends Activity {
TextView textView;
MyLocationListener myLocationListener;
LocationManager lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textView = (TextView)findViewById(R.id.message);
addLocationListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void addLocationListener()
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
final String PROVIDER = lm.getBestProvider(c, true);
this.myLocationListener = new MyLocationListener();
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, this.myLocationListener);
//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0.0F, myLocationListener);
Log.d("LOC_SERVICE", "Service RUNNING!");
}
public void updateLocation(Location location)
{
double latitude, longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
int mph = convertSpeed(location.getSpeed());
Log.d("LOC_SERVICE", "mph: "+mph);
this.textView.setText(this.textView.getText()+"\n"+"lat: "+latitude+" lng: "+longitude+" mph: "+mph);
}
private int convertSpeed(float speed) {
int mph =(int)(2.236936D * speed);
return mph;
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.d("LOC_SERVICE", "Listener RUNNING!");
updateLocation(location);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
You need to use permission first:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Next you inside onCreate() method use below code to get access to GPS.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 1, this);
}
Now if GPS is not enabled then you need to refer below code. For detailed explanation, you can refer how to get[DEAD LINK] [current location in android]1 tutorial.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Here we have used intents to redirect user to location settings page so that he can enable the GPS under location settings.
you can achieve this easily. you have to write code in main activity. and Main activity implements Locationlistner interface. and overload its four methods. here i'am retrieving my Longitude and Latitide co-ordinates in a textview when application started. and you have to give permission for access location in your manifest file.
as under my code.
package com.nisarg.gpsdemo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView)findViewById(R.id.textView);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
#Override
public void onLocationChanged(Location location) {
double longitude=location.getLongitude();
double latitude=location.getLatitude();
textview.setText("Longitude: "+longitude+" Latitide: "+latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
and you have to give permission like this in manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And last warning.
you have to give permission to your application and start mobile data and GPS before you open application. either it will be crashed.
that's it.
hope it will help you. :)

Internet Permission for Location Updates

Do I really need Internet Permission to get the current Location through either GPS or Network Provider.
I run the below code without giving Internet Permission .It is working fine.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.practice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.practice.LocationActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.practice.AlarmReceiver" >
</receiver>
</application>
</manifest>
LocationService.java
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class LocationService implements LocationListener {
private final Context mContext;
private boolean isGPSEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location location;
private double latitude;
private double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public LocationService(Context context) {
this.mContext = context;
location = getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("network ", isNetworkEnabled+"");
Log.i("GPS ", isGPSEnabled+"");
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
canGetLocation = true;
if (isGPSEnabled) {
if (locationManager != null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("GPS", "GPS");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
Log.i("location", location+"");
if (location == null) {
Log.i("Location Manager", locationManager+"");
if (locationManager != null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("NETWORK", "NETWORK");
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public boolean canGetLocation() {
return canGetLocation;
}
public void onLocationChanged(Location location) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationActivity.java
package com.example.practice;
import com.example.location.LocationService;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class LocationActivity extends Activity {
LocationService locationService;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
button=(Button)findViewById(R.id.btn_location);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationService=new LocationService(LocationActivity.this);
if(locationService.canGetLocation())
{
Location location=locationService.getLocation();
Toast.makeText(LocationActivity.this, location.getLatitude()+ " "+location.getLongitude(),Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.location, menu);
return true;
}
}
Yes it will work as you added the location permission and also see this on developers site http://developer.android.com/training/location/retrieve-current.html

GPS not working

What I am doing is trying to get a basic GPS working and can't figure out the problem (there is no errors coming up). When i run it on the emulator it crashes. I am using android 2.2
package Weather.app;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class WeatherAppActivity extends Activity{
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected LocationListener MyLocationListener;
protected Button findButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findButton = (Button) findViewById(R.id.findButton);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
(LocationListener) this
);
findButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(WeatherAppActivity.this, message,
Toast.LENGTH_LONG).show();
}
final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(WeatherAppActivity.this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(WeatherAppActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
}
This is also in my manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
I have updated this code as I have made a few changes
Here is one example of working basic GPS activity:
public class UseGpsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
double lati = loc.getLatitude();
double longi = loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + lati + "Longitud = " + longi;
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Unless some code is missing in your post MyLocationListener (you should not user upper case identifiers for instance fields!) is not initialized when passing the reference (i.e. null) to requestLocationUpdates().
You don't need to create another LocationListener, the statement
WeatherAppActivity extends Activity implements LocationListener
and the overriden methods
#Override
public void onLocationChanged(Location location)
etc means you have one in your main class already, so get rid of the inner class MyLocationListener completely.
Put your Toast code etc inside the overriden listener methods in the main class.
Then in onCreate() have :
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
this
);
I have a tutorial on Android location services on my blog. I'm not sure of your specific error but you can look at the code to see if it helps you!
http://www.scotthelme.co.uk/blog/android-location-services/

Categories

Resources