i'm developing an app to send user location via sms after a fixed time and if the phone restarts the app should starts automatically in the background without any launcher activity. I have quiet accomplished my task I'm only facing problem in getting location, as gps takes some time and app gets crash when it does not find any location.
here is my code of main Activity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLocationTracking();
}
private void startLocationTracking()
{
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(MainActivity.this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exjfkd"+e);
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE,10);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*600, sender1);
System.out.println("set timer");
}
}
public class AlarmReceiver extends BroadcastReceiver{
long time = 600* 1000;
long distance = 10;
#SuppressLint("NewApi")
#Override
public void onReceive(final Context context, Intent intent) {
System.out.println("alarm receiver....");
Intent service = new Intent(context, MyService.class);
context.startService(service);
//Start App On Boot Start Up
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent App = new Intent(context, MainActivity.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
try{
LocationManager locationManager = (LocationManager)context
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, time,
distance, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId(); // returns IMEI number
String phoneNo = "+923362243969";
String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
}
catch (Exception e) {
e.printStackTrace();
}
this.abortBroadcast();
}
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
}
};
}
i'm little confuse in logic I want my app to send sms when gps coordinates are available. and if gps in disabled on the phone it if network is available on the phone it should get the location through network and send it through the network.
EDIT
Your app is crashing since for the first time after reboot GPS/network won't have the lastknowlocation since
Location location = locationManager.getLastKnownLocation(provider);
In this line you will be receiving location as null.
String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
and in this line you will get the null pointer exception since location.getLatitude() is not posible.
so before this code try to check location!=null.
if(location!=null){
String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
}
Use this method to know the status of GPS availablity
public boolean isgpsavailable(Activity activity) {
LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
boolean result = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return result;
}
Then put your code into a if(isgpsavailable(this)){...} Statement
You can send SMS with the android.telephony package. You can see how add to your project here: How do I add ITelephony.aidl to eclipse?
Something like this permit you send a textSMS:
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, scAddress, texto, null, null);
Hope it helps you!!
Related
I'm making an app to send current location of user via sms after fixed time but it always send the same coordinates. I read lot of links but I don't know where is the mistake kindly tell me what is the problem in my code you can edit the code as u like
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
long time = 600* 1000;
long distance = 10;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
Location location;
String device_id;
String phoneNo = "+923362243969";
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("alarm receiver....");
Intent service = new Intent(context, MyService.class);
context.startService(service);
//Start App On device restart
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent App = new Intent(context, MainActivity.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
device_id = tm.getDeviceId(); // returns IMEI number
try {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,time,distance, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
location.getLatitude();
location.getLongitude();
String Text = " From GPS: Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
this.abortBroadcast();
}
}
}
}
else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time,distance, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
location.getLatitude();
location.getLongitude();
String Text = " From Network: Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
this.abortBroadcast();
}
}
}
}
} catch (Exception e) {
Toast.makeText(context, "no connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#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
}
}
This is where you need to get the location. Take Longitude and Latitude variables as public members and updated them in the below event.
double Latitude, Longitude;
#Override
public void onLocationChanged(Location location) {
Longitude = location.getLongitude();
Latitude = location.getLatitude();
}
And while sending a SMS, put Longitude and Latitude variables in place of location.
i've an app that sends gps coordinates on a hardcoded number via sms but it always sends the same coordinates and never give the new location. i don't know where i'm making mistake please help me to solve the problem.
public class AlarmReceiver extends BroadcastReceiver implements LocationListener{
long time = 900 * 1000;
long distance = 10;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
Location location;
#SuppressLint("NewApi")
#Override
public void onReceive(final Context context, Intent intent) {
System.out.println("alarm receiver....");
Intent service = new Intent(context, MyService.class);
context.startService(service);
//Start App On Boot Start Up
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent App = new Intent(context, MainActivity.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
try {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,time,distance, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
location.getLatitude();
location.getLongitude();
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId(); // returns IMEI number
String phoneNo = "+923409090000";
String Text = " From GPS: Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
this.abortBroadcast();
}
} }
} else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time,distance, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
location.getLatitude();
location.getLongitude();
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId(); // returns IMEI number
String phoneNo = "+9234090900000";
String Text = " From Network: Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
this.abortBroadcast();
}
}
}
}
} catch (Exception e) {
Toast.makeText(context, "no connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
#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
}
}
Hi can any body show me how to run this code in service without activity, i have done this code in an activity but i dont want it to be an application i need it to be in a service only just to display it on service thank you i have tried but my activity displaying for once in 30 mins.
this is my code:
public class gps extends Activity implements LocationListener {
LocationManager manager;
String closestStation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
cur_cal.add(Calendar.MINUTE, 15);
Log.d("Testing", "Calender Set time:" + cur_cal.getTime());
Intent intent = new Intent(gps.this, gps_back_process.class);
PendingIntent pintent = PendingIntent.getService(gps.this, 0,
intent, 0);
AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP,
cur_cal.getTimeInMillis(), 1000 * 60 * 15, pintent);
alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(),
pintent);
Log.d("Testing", "alarm manager set");
Toast.makeText(this, "gps_back_process.onCreate()",
Toast.LENGTH_LONG).show();
}
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else
{
tv.setText("Last known location not found. Waiting for updated location...");
}
manager.requestLocationUpdates(providerName, 1000*60*30 , 1 , this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting gps NETWORK ID : " + "");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File(Environment.getExternalStorageDirectory() + "/GpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm, dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
// text+=","+currentDateandTime;
buf.append(text + "," + currentDateandTime);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.extends service class instead of Activity class and
2. put your code into oncreate()
3.add your service into manefest.
4.call service from activity once like
Intent service = new Intent(context, localService.class);
context.startService(service);
follow this tutorial.
hi i am doing a application based on gps,i use gps as service for my project ,when gps is turn on it show the location correctly and application runs fine ,but after that i exit from my app completely and when the gps turned off the it shows crash message.which mean even if l leave or exit my app the service class is still running ,and also app get crash if i turn off gps when app is running ,but if i did not turn of gps it work fine.Now how can i solve this problem. i will show my service class used for gps
public class Gps_Service extends Service {
TextView txtv;
List<Address> myList;
String addressStr;
LocationManager lm;
LocationListener ll;
SQLiteDatabase DiaryDB = null;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("########### serviceOnCreate");
// Toast.makeText(this, "GPS Service started(Diary)", Toast.LENGTH_LONG).show();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
#Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "GPS Service Destroyed(Diary)", Toast.LENGTH_LONG).show();
lm.removeUpdates(ll);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
// Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class mylocationlistener implements LocationListener
{
public void onLocationChanged(Location location)
{
if (location != null) {
Geocoder myLocation = new Geocoder(Gps_Service.this, Locale.getDefault());
// Toast.makeText(MyService.this,location.getLatitude() + " " + location.getLongitude() +"\n",Toast.LENGTH_LONG).show();
// DiaryDB = MyService.this.openOrCreateDatabase("DIARY_DATABASE", MODE_PRIVATE, null);
// DiaryDB.execSQL("INSERT INTO Locations(LATITUDE, LONGITUDE) VALUES('" +location.getLatitude()+"','"+location.getLongitude()+"')");
// DiaryDB.close();
// ParseTweetsActivity.latitude = ""+location.getLatitude();
//ParseTweetsActivity.longitude = ""+location.getLongitude();
AndroidGoogleMapsActivity.lats = Double.parseDouble(""+location.getLatitude());
AndroidGoogleMapsActivity.longt = Double.parseDouble(""+location.getLongitude());
Advertiser_get_direction.latitudefrom = Double.parseDouble(""+location.getLongitude());
Advertiser_get_direction.longtitudefrom = Double.parseDouble(""+location.getLongitude());
AndroidGoogleMapsActivity.longt = Double.parseDouble(""+location.getLongitude());
System.out.println("saaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+AndroidGoogleMapsActivity.lats);
// ParseTweetsActivity.load();
try
{
myList = myLocation.getFromLocation(location.getLatitude(),location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if(myList!=null)
{
Address address = (Address) myList.get(0);
addressStr = "";
addressStr += address.getAddressLine(0) + "\n";
addressStr += address.getAddressLine(1) + "\n";
addressStr += "Country name "+address.getCountryName() + "\n";
addressStr += "Locality "+address.getLocality() + "\n";
addressStr += "Country code "+address.getCountryCode() + "\n";
addressStr += "Admin Area "+address.getAdminArea() + "\n";
addressStr += "SubAdmin Area "+address.getSubAdminArea() + "\n";
addressStr += "PostalCode "+address.getPostalCode() + "\n";
// txtv.append(location.getLatitude() + " " + location.getLongitude() +"\n");
// txtv.append(addressStr+"\n");
System.out.println(location.getLatitude() + " " + location.getLongitude() +"\n");
lm.removeUpdates(ll);
}
}
}
public void onProviderDisabled(String provider)
{
// Toast.makeText(MyService.this,"Provider Disabled",Toast.LENGTH_LONG).show();
txtv.setText("");
}
public void onProviderEnabled(String provider)
{
// Toast.makeText(MyService.this,"Provider Enabled.....",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
You have declared a TextView within your Service. That's not good. TextView is a UI component and doesn't belong on the service.
In your onProviderDisabled() method, you call txtv.setText(""); which will probably crash because txtv is null. This is probably why your app is crashing when you disable GPS.
Change your code from
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
to following
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0,ll);
}
I had a problem like this when i didn`t release listener in the onDestroy().
Try to add the following code:
lm.unregisterListener(ll);
How do I use
requestLocationUpdates(long minTime, float minDistance, Criteria criteria,
PendingIntent intent)
In BroadcastReciver so that I can keep getting GPS coordinates.
Do I have to create a separate class for the LocationListener ?
Goal of my project is when I receive BOOT_COMPLETED to start getting GPS lats and longs periodically.
Code I tried is :
public class MobileViaNetReceiver extends BroadcastReceiver {
LocationManager locmgr = null;
String android_id;
DbAdapter_GPS db;
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
startGPS(context);
} else {
Log.i("MobileViaNetReceiver", "Received unexpected intent "
+ intent.toString());
}
}
public void startGPS(Context context) {
Toast.makeText(context, "Waiting for location...", Toast.LENGTH_SHORT)
.show();
db = new DbAdapter_GPS(context);
db.open();
android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
Log.i("MobileViaNetReceiver", "Android id is _ _ _ _ _ _" + android_id);
locmgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5,
onLocationChange);
}
LocationListener onLocationChange = new LocationListener() {
public void onLocationChanged(Location loc) {
// sets and displays the lat/long when a location is provided
Log.i("MobileViaNetReceiver", "In onLocationChanged .....");
String latlong = "Lat: " + loc.getLatitude() + " Long: "
+ loc.getLongitude();
// Toast.makeText(this, latlong, Toast.LENGTH_SHORT).show();
Log.i("MobileViaNetReceiver", latlong);
try {
db.insertGPSCoordinates(android_id,
Double.toString(loc.getLatitude()),
Double.toString(loc.getLongitude()));
} catch (Exception e) {
Log.i("MobileViaNetReceiver",
"db error catch _ _ _ _ " + e.getMessage());
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
//pauses listener while app is inactive
/*#Override
public void onPause() {
super.onPause();
locmgr.removeUpdates(onLocationChange);
}
//reactivates listener when app is resumed
#Override
public void onResume() {
super.onResume();
locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, onLocationChange);
}*/
}
There are two ways of doing this:
Use the method that you are and register a BroadcastReceiver which has an intent filter which matches the Intent that is held within your PendingIntent (2.3+) or, if you are only interested in a single location provider, requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent) (1.5+) instead.
Register a LocaltionListener using the requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener) method of LocationManager.
I think that you are getting a little confused because you can handle the location update using either a BroadcastReceiver or a LocationListener - you don't need both. The method of registering for updates is very similar, but how you receive them is really very different.
A BroadcastReceiver will allow your app / service to be woken even if it is not currently running. Shutting down your service when it is not running will significantly reduce the impact that you have on your users' batteries, and minimise the chance of a Task Killer app from terminating your service.
Whereas a LocationListener will require you to keep your service running otherwise your LocationListener will die when your service shuts down. You risk Task Killer apps killing your service with extreme prejudice if you use this approach.
From your question, I suspect that you need to use the BroadcastReceiver method .
public class MobileViaNetReceiver extends BroadcastReceiver {
private static final String TAG = "MobileViaNetReceiver"; // please
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Log.i(TAG, "Boot : registered for location updates");
LocationManager lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(context, this.getClass());
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,5,pi);
} else {
String locationKey = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(locationKey)) {
Location loc = (Location) intent.getExtras().get(locationKey);
Log.i(TAG, "Location Received");
try {
DbAdapter_GPS db = new DbAdapter_GPS(context);//what's this
db.open();
String android_id = Secure.getString(
context.getContentResolver(), Secure.ANDROID_ID);
Log.i(TAG, "Android id is :" + android_id);
db.insertGPSCoordinates(android_id,
Double.toString(loc.getLatitude()),
Double.toString(loc.getLongitude()));
} catch (Exception e) { // NEVER catch generic "Exception"
Log.i(TAG, "db error catch :" + e.getMessage());
}
}
}
}
}