I had service that run by BrodcastReceiver which suppose to run and give me the GPS data that I requested and I stopped it after I did what suppose to be done, but I notice that It did not provide me with the data that requested and did not stop too , any body can help me in figuring out my problem
the code is below and the service tested in real device:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class GpsService extends Service implements LocationListener{
static LocationManager mlocManager;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
mlocManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,0, 0,this);
}
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
// Here to stop the service and make it finish its task
SystemClock.sleep(40000);
// stop the Gps system by this application
mlocManager.removeUpdates(this);
//Here to stop the service by itself
stopSelf();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
do you have the correct permissions on the manifest?
why do you make the service sleep and for so long? the service works on the UI thread , and such a thing can cause the service to be killed automatically by the system after about 5 seconds because the ui thread doesn't respond.
if you wish to delay the stopping and/or showing of the toast , either use Handler (and postDelayed) , or use asyncTask , or something of your own .
do you have the gps turned on? have you considered using a fake location app or the emulator for this task ?
good luck .
Related
Hi I am writing program which fetches users current lattitude and longitude every 5 minutes using Alarmmanager and store the value in shared preferences.I want to run this search backgroun so iam using service.I want to stop the service after fetching the lattitude and longitude to avoid battery drain.This is my code
CurrentLocation.java
import com.google.android.gms.maps.model.LatLng;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class CurrentLocation extends Service implements LocationListener {
private Context mcontext;
SharedPreferences shprefs;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.mcontext=this;
getlocation();
}
private void getlocation() {
// TODO Auto-generated method stub
Log.i("evvterer", "mnbj");
LocationManager locationManager = (LocationManager) mcontext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
shprefs=PreferenceManager.getDefaultSharedPreferences(CurrentLocation.this);
double latitude=location.getLatitude();
Editor edit=shprefs.edit();
edit.putString("Ltd", ""+latitude);
edit.commit();
double longitude=location.getLongitude();
Editor edits=shprefs.edit();
edits.putString("Lngtd", ""+longitude);
edits.commit();
LatLng loca=new LatLng(latitude,longitude);
}
#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
}
}
please help me
Thanks in advance
use Broadcast receiver instead of service because broadcast receiver intent trigger when your condition meet so use broadcast for fetches users current latitude and longitude every 5 minutes.:) from broadcast receiver your battery is not reduce very much as service do
As you use returning null from onBind, you may be using startService() to start your CurrentLocation service.
So when you are done with your CurrentLocation service, simpally call stopService (Intent service)
But if you have used bindService then you have to use unBindService().
To stop service at exact time, you can call a method in your activity at end of onLocationChanged() and from that method stop the service.
Or send a message to handler associated with your Activity to stop the service.
And add your code to start the service, so that it will help others to answer your question.
I'm pretty new to android, and this is my first post here, so please be kind! :-)
I'm trying to create a service which runs in the background and does a location update every x minutes. To run it every x minutes I'm using the AlarmManager, as described here: Alarm Manager Example
Here's what I've got:
package com.example.service1;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
public class Scheduler extends BroadcastReceiver{
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//Code which is executed every X seconds/minutes
getLocation(context);
//End of Code
wl.release();
}
public void setScheduler(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Scheduler.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 20, pi);
}
//Method to get the Location
public void getLocation(Context context) {
Log.e("null","getLocation");
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e(null, "location change");
makeUseOfLocation(location);
}
#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
}
};
}
//Method to work with the location Data; Instance of Point is created
public void makeUseOfLocation(Location location) {
Log.e(null,"makeuse");
Log.e(null,location.getLatitude() + "");
}
}
getLocation() is called every 20 seconds, but then it never runs onLocationChanged() (I use the EmulatorControl in Eclipse to change the location).
I had the same problem before when I used the ScheduledExecutorService instead of the AlarmManager.
Can anyone help me?
Looking at your code I never see the call to locationManager.requestLocationUpdates() with your listener as an argument.
This means that your listener is never registered with the location manager, and therefore does not get called.
You probably only want to register one listener, instead of registering a new one every time.
Try this..
protected void updateNotification() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener {
public void onLocationChanged(Location location){
if(location!=null){
if(location.hasAccuracy()){
dumpLocation(location);
}else{
dumpLocation(location);
}
}
}
public void onProviderDisabled(String provider){
Log.v("Loc Update","\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider){
Log.v("Loc Update","\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras){
Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
+ status + ", extras=" + extras);
}
Here is my code, i cant seem to get the coordinates while using NETWORK_PROVIDER. onLocationChange() does not seem to fire. I will appreciate the help.
package com.networkprovider;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
public class networkProvider extends Activity {
EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText1=(EditText)findViewById(R.id.editText1);
}
#Override
protected void onStart() {
LocationManager locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener=new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location location) {
String loc=String.valueOf(location.getLatitude())+","+String.valueOf(location.getLongitude());
Toast.makeText(getApplicationContext(),loc, Toast.LENGTH_LONG).show();
//editText1.setText(loc);
}
};
boolean isEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isEnabled)
{
Toast.makeText(getApplicationContext(),"Enabled", Toast.LENGTH_LONG).show();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}
else
{
Toast.makeText(getApplicationContext(),"Not Enabled!", Toast.LENGTH_LONG).show();
}
super.onStart();
}
}
I ran this code and it returned me my location in a toast
check that you have
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
in your manifest or that the device has network locations turned on :)
It may be a silly answer, but are you sure it Should be triggered?
As long as you stay indoors, as the precision of the network is really low, maybe you can't move enough to trigger onLocationChange(). At my home, network precision is about 1km, so you have to get a really big building to use this kind of data to do localisation...
Antoine
My app includes activity of getting coordinates of my current location and then showing the route to a destination for which i have given the coordinates.The problem is it takes hours to load the map and get the route.If anybody could suggest me how to get it done at a faster rate please.And i'm using The Map application present in mobile for getting the map functionality.
Here's the code i'm using
package com.map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
public class MapRouteActivity extends Activity {
#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);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+loc.getLatitude()+","+loc.getLongitude()+"&daddr=18.5204303,73.8567437"));
startActivity(intent);
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
GPS takes time to get a fix. It has to scan a lot of frequencies before it actually triangluates your position. The code that you have written launches Google Maps on getting a valid fix. ( on onLocationChanged() )
Instead you may use MapView. That way your map will be loaded much faster and you don't even have to wait for a proper fix.
I have created one service and also added it in manifest. When I use timer to call this service periodically and in timer I have used location manager to get location of user contin. But there is error like that:
05-11 11:57:17.574:
ERROR/AndroidRuntime(3305):
java.lang.RuntimeException: Can't
create handler inside thread that has
not called Looper.prepare()
Tell me where is problem in my code.
code is here
package com.collabera.labs.sai;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
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 SimpleService extends Service {
Timer mytimer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
mytimer = new Timer();
mytimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//getdata();
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
}
},0,1000);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
public void getdata()
{
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitude = "
+ loc.getLatitude() + "Longitude = " + loc.getLongitude();
/*Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT)
.show();*/
Log.d("TAG", "Starting..");
}
#Override
public void onProviderDisabled(String provider) {
/*Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();*/
}
#Override
public void onProviderEnabled(String provider) {
/*Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}/* End of Class MyLocationListener */
}
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
You can't modify UI from the non-UI thread. Services are never executed on the UI thread. Log this instead of making a Toast.