I wish to access user's position using gps system of phone.
In manifest I've included
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I get null location at .appLocationService.getLocation();
public class MainActivity extends AppCompatActivity {
AppLocationService appLocationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(MainActivity.this);
}
public void OpenAddress(View v) {
appLocationService =new AppLocationService(MainActivity.this);
Location location = appLocationService.getLocation();
if (location != null) {
// getting co-ordinates and address
}
else showSettingsAlert();
}
}
I get null location at .getLastKnownLocation(provider);Here i get all locations from all providers. But all seem to return null location
public class AppLocationService extends Service implements LocationListener {
public AppLocationService(){}
Context mcontext;protected LocationManager locationManager;Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
mcontext=context;
}
public Location getLocation() {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) //enabling it
else {
if (locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) continue;
if(bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy())
bestLocation=l;
}
return bestLocation;
}
}
return null;
}
Here is the complete solution. I have wrote it and works pretty good on my device. I have shared on github as well.
Github: click here
MainActivity.java
public class MainActivity extends AppCompatActivity {
AppLocationService mAppLocationService;
boolean mBounded;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.callLocation);
}
public void OpenAddress(View view){
Location location = mAppLocationService.getLastKnownLocation();
if (location != null){
Log.e("location","latitude:"+location.getLatitude()+" longtitude"+location.getLongitude());
}else {
Log.e("location","location return null");
}
}
ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
AppLocationService.LocalBinder binder = (AppLocationService.LocalBinder) service;
mAppLocationService = binder.getInstance();
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mAppLocationService = null;
}
};
#Override
protected void onStart() {
super.onStart();
Intent i = new Intent(MainActivity.this,AppLocationService.class);
bindService(i,mConnection,BIND_AUTO_CREATE);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBounded){
unbindService(mConnection);
mBounded = false;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/callLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="OpenAddress"
android:text="Location"/>
</android.support.constraint.ConstraintLayout>
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
Location location;
Context mcontext;
protected LocationManager locationManager;
private static final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
IBinder binder = new LocalBinder();
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class LocalBinder extends Binder{
public AppLocationService getInstance(){
return AppLocationService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public Location getLastKnownLocation() {
final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
Location bestLocation = null;
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
if (Permissions.getInstance(this).checkLocationPermission()) {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
}
} else {
Log.e("check", "Gps is not enable");
}
return bestLocation;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shahz.testing">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".AppLocationService"/>
</application>
</manifest>
Related
I am building app that tracks distance traveled. At the moment, I am having trouble displaying the coordinates. The code runs, but the Distance, which I've set to display the coordinates when Start is clicked, displays 0.00 when clicked.
public class MainActivity extends Activity {
private Button historyButton, startButton, stopButton;
private TextView Distance;
double currentDistance;
private SensorManager sensorManager;
private Chronometer TimeRan;
private LocationManager mLocManager;
private LocationListener location;
double longitude, latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing all buttons and textviews
historyButton = (Button) findViewById(R.id.History);
startButton = (Button) findViewById(R.id.Start);
stopButton = (Button) findViewById(R.id.Stop);
Distance = (TextView) findViewById(R.id.Distance);
TimeRan = (Chronometer) findViewById(R.id.Time_Spent);
mLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
location = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentDistance += .01;
Distance.append("/n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 100:
configureButton();
break;
default:
break;
}
}
public void configureButton(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,100);
}
return;
}
//Request update every minute or 16 meters
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ignore permission
mLocManager.requestLocationUpdates("gps", 60000, 16, location);
}
});
};
public void GoToHistory(View v) {
Intent history = new Intent(this, History.class);
startActivity(history);
}
protected void EndWorkout(View v){
TimeRan.stop();
//ignore permission
mLocManager.removeUpdates(location);
}
}
Here is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stuyk.runningapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.sensor.stepcounter"/>
<uses-feature android:name="android.hardware.sensor.stepdetector"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".History" />
</application>
</manifest>
locationManager.requestLocationUpdates(
provider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
You should set MINIMUM_TIME_BETWEEN_UPDATES to time that you want it to be updated frequently and set MINIMUM_DISTANCE_CHANGE_FOR_UPDATES distance the update will change according to your location status.
I am trying to get the location of the device by the network provider.
if i am using GPS is working good.
but when i try to locate it by my provider is all the time return false.
i make sure that in the manifest i have all the permissions that i need:
this is my manifest:
<permission
android:name="com.example.matant.gpsportclient.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.example.matant.gpsportclient.permission.MAPS_RECEIVE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.example.matant.gpsportclient.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.galaxystech.pushnotifications.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and this is my Location class:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating;
private LocationManager locationManager;
private Location currentLoc;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.d("gpsEnabled",String.valueOf(gpsEnabled));
Log.d("networkEnabled",String.valueOf(networkEnabled));
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on settings and make sure your GPS is enabled");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
i found the problem.
in my device setting i need to configure that the device will use only WiFi and cellular networks in order to retrieve the location.
When I test the application using the Eclipse DDMS - it works, onlocationchanged called
but when I install the app on your tablet - nothing
my source
public class Fragment_1 extends Fragment{
final String LOG_TAG = "myLogs";
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
private String bestProvider;
private Context contextActivity;
private LocationManager locationManager;
private MyLocationListener locationListener;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
contextActivity = getActivity();
locationManager = (LocationManager) contextActivity.getSystemService(contextActivity.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
bestProvider = locationManager.getBestProvider(crit, false);
locationListener = MyLocationListener.createMyLocationListener(this);
locationManager.requestLocationUpdates(
bestProvider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
locationListener);
}
and my class MyLocationListener
ublic class MyLocationListener implements LocationListener {
private Fragment_1 fragment;
private static MyLocationListener myLocationListener;
public MyLocationListener(Fragment_1 fragment_1) {
// TODO Auto-generated constructor stub
fragment = fragment_1;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(fragment.getActivity() !=null) {
TextView textViev = (TextView)fragment.getActivity().findViewById(R.id.textView1);
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
textViev.setText(message);}
}
public static MyLocationListener createMyLocationListener (Fragment_1 fragment_1) {
if (myLocationListener == null) {
myLocationListener = new MyLocationListener(fragment_1);
} else {
myLocationListener.setFragment(fragment_1);
}
return myLocationListener;
}
private void setFragment (Fragment_1 fragment){
this.fragment = fragment;
}
}
and permission in the manifest
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
My application works as follows:
I have one location listener to every activity
My location listener(which contains location listener) send broadcast on location changed
All activities have broadcast receiver which allows them to set location on map
It has to be working like that, but even my service doesn't start. I'm exhausted writing this app so I place my code here, maybe I overlooked some simple issue. I need help with that topic:
GPS Service:
// package and imports
public class GeoService extends Service {
LocationListener GPSLocationListener, NetworkLocationListener;
LocationManager locationManager;
private IBinder mBinder;
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getPosition();
return Service.START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
getPosition();
if (mBinder == null) mBinder = new GeoBinder();
return mBinder;
}
private void getPosition() {
GPSLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendPosition(location);
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), provider + " is now disabled. Turn it on to find better GPS position.", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), provider.toUpperCase() + " is now enabled. Waiting for better position..", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case 0:
case 1:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, NetworkLocationListener);
break;
case 2:
locationManager.removeUpdates(NetworkLocationListener);
break;
}
}
};
NetworkLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendPosition(location);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, GPSLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, NetworkLocationListener);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) alert();
}
private void alert() {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Internet connection and GPS are not avaiable!.").setCancelable(false).setTitle("No location provider!").setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Change settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
}
}).create().show();
}
void sendPosition(Location location) {
Intent gpsPosition = new Intent();
gpsPosition.putExtra("location", location);
gpsPosition.setAction(Context.LOCATION_SERVICE);
sendBroadcast(gpsPosition);
}
public GeoPoint getGeoPoint(final Location loc) {
int lat = (int) (loc.getLatitude() * 1e6);
int lon = (int) (loc.getLongitude() * 1e6);
return new GeoPoint(lat, lon);
}
public GeoPoint getLastLocation() {
GeoPoint lastKnownPoint;
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation == null) lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastKnownLocation != null) lastKnownPoint = getGeoPoint(lastKnownLocation);
else lastKnownPoint = new GeoPoint((int) (51.110582 * 1E6), (int) (17.031509 * 1E6));
return lastKnownPoint;
}
#Override
public void onDestroy() {
locationManager.removeUpdates(GPSLocationListener);
locationManager.removeUpdates(NetworkLocationListener);
}
public class GeoBinder extends Binder {
public GeoService getService() {
return GeoService.this;
}
}
}
One of Activities: (I tried to start or bind service but none method seems to be working).
// package and imports
public class ShareLocationActivity extends MapActivity {
private final int PICK_CONTACT = 123;
MapView.LayoutParams mapMarkerParams;
MapController mapController;
Location lastLocation;
ImageView mapMarker;
GeoPoint current;
MapView map;
private ServiceConnection mConnection;
GeoService mService;
boolean mBound = false;
BroadcastReceiver locationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setPosition((Location) intent.getParcelableExtra("location"));
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_location);
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
GeoBinder binder = (GeoBinder) service;
mService = binder.getService();
mBound = true;
mapController = map.getController();
mapController.setCenter(mService.getLastLocation());
mapController.setZoom(17);
}
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
Intent intent = new Intent(this, GeoService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
map = (MapView) findViewById(R.id.shareMapView);
map.setBuiltInZoomControls(true);
map.setSaveEnabled(true);
mapMarker = new ImageView(getApplicationContext());
mapMarker.setImageResource(android.R.drawable.presence_online);
Button share = (Button) findViewById(R.id.shareActivityButton);
share.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent contacts_intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contacts_intent, PICK_CONTACT);
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(Context.ACTIVITY_SERVICE);
registerReceiver(locationReceiver, filter);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
if (current != null) sendSms(data);
else Toast.makeText(getApplicationContext(), "No GPS data yet..", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mBound) {
Intent intent = new Intent(this, GeoService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
};
#Override
protected void onPause() {
map.removeAllViews();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
map.removeAllViews();
}
void setPosition(Location location) {
map.removeAllViews();
current = mService.getGeoPoint(location);
mapMarkerParams = new MapView.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, current, MapView.LayoutParams.TOP_LEFT);
map.addView(mapMarker, mapMarkerParams);
mapController.setCenter(current);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
And to be sure Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gps.counter"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.location" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application
android:icon="#drawable/ico"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<uses-library android:name="com.google.android.maps" />
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SaveLocationActivity" />
<activity android:name=".ShareLocationActivity" />
<activity android:name=".RecordTrackActivity" />
<activity android:name=".SettingsActivity" />
<service
android:name=".GeoService"
android:enabled="true" />
</application>
</manifest>
The solution is to keep service and activity which uses it in one package.
It is small issue but can be big problem for someone.
I have a problem when the service is started: the appliaction shows a force close message.
my startservice in the main activity looks like this:
startService(new Intent(Main.this,GPSService.class));
GPSService.class
public class GPSService extends Service implements LocationListener {
LocationManager locationManager;
double x1,x2;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location loc)
{
x1=loc.getAltitude();
x2=loc.getLatitude();
}
public void onProviderEnabled(String s){
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void onProviderDisabled(String s){
//locationManager.removeUpdates(this);
//x1=0;
// x2=0;
}
public void onStatusChanged(String s, int i, Bundle b){}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
}
You need to give following permissions in androidManifest.xml
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES">