Running Gps in Background service - android

I need to track user location continuously whether my application is running or not, for this i have a created a background Service and calculate latitude and longitude on Asyntask in this service , my code is running well in emulator but on device it got crashed after saying application is not responding. However log cat does not show any error. Please anybody help me. Thanks in Advance.
Here is MyService.java
public class MyService extends Service {
// flag for GPS status
public static LocationManager manager;
public static boolean isGPSEnabled = false;
public static double lattitude = 0;
public static double longitude = 0;
int count = 0;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
MyFile myFile;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} // method ends
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
System.out.println("On Start Command is called ");
return START_STICKY;
} // method ends
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("Service is created//////////// ");
// start asyntask to get locations
Context mContext = MainActivity.getContextForService();
if(mContext!=null)
{
myFile = new MyFile(mContext);
}
new GetLocations().execute();
}// on create ends
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("Service is Destroyed //////////// ");
if (manager != null && isGPSEnabled == true) {
manager.removeUpdates(mylistener);
System.out.println("Service is Destroyed under if //////////// ");
}
} // method ends
public class GetLocations extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = manager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = manager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
/*Criteria criteria = new Criteria();
String bestProvider = manager.getBestProvider(criteria, false);
Location location = manager.getLastKnownLocation(bestProvider);
double lat =location.getLatitude();
double longi =location.getLongitude();
System.out.println("getting location continous ////// Lattti " +location.getLatitude()
);
System.out.println("getting location continous ////// LONGITU " +
location.getLongitude());*/
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, mylistener);
File root = new File(Environment.getExternalStorageDirectory(),
"Notes");
if (!root.exists()) {
root.mkdirs();
}
} else {
Toast.makeText(MainActivity.getContextForService(),
"Please oN Gps ", Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// getting current lattitude and longitude
return null;
}// method ends
}// asyntask class ends
void handleLocationChanged(Location loc) {
lattitude = loc.getLatitude();
longitude = loc.getLongitude();
if (count == 0) {
Toast.makeText(MainActivity.getContextForService(),
"lat is " + lattitude + " long is " + longitude,
Toast.LENGTH_LONG).show();
count = count + 1;
}
System.out.println("getting location continous ////// Lattti " +
lattitude);
System.out.println("getting location continous ////// LONGITU " +
longitude);
generateNoteOnSD("GpsTesting", "lattitude is" + lattitude + "\n"
+ " longitude" + longitude);
} // method ends
public LocationListener mylistener = new LocationListener() {
#Override
public void onLocationChanged(Location loc) {
handleLocationChanged(loc);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
// Toast.makeText(mContext, "Gps is disable",
// Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
// Toast.makeText(mContext, "Gps is on", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
// Toast.makeText(appcontext, "Gps status is chnged ",
// Toast.LENGTH_SHORT).show();
}
};
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.getContextForService());
// Setting Dialog Title
alertDialog.setTitle("Alert");
// 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);
getApplicationContext().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();
}// method ends
// method for sending notiifcation
public void sendNotification() {
int MY_NOTIFICATION_ID = 1;
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), 0,
new Intent(MainActivity.getContextForService(),
MainActivity.class), 0);
Notification myNotification = new NotificationCompat.Builder(
getApplicationContext())
.setContentTitle("Notification for Lat and Long")
.setContentText("hi testing notiifaction on lat and long")
.setTicker(" ToDoList Notification")
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher).build();
NotificationManager notificationManager = (NotificationManager) MainActivity
.getContextForService().getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
} // method ends
// writing file on
public void generateNoteOnSD(String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(),
"Gps_Data");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} // method ends
} // final class ends
Here is MainActivity.java
public class MainActivity extends Activity {
Button btnStart, btnStop;
public static Context mContext;
Intent it;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(getIntent());
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(getIntent());
}
});
} // on create ends
#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 Intent getIntent() {
it = new Intent(mContext, MyService.class);
return it;
} // method ends
public static Context getContextForService() {
return mContext;
} // methods ends
} // final class ends

Man you are doing very heavy task on your main thread which is
#Override
public void onLocationChanged(Location loc) {
handleLocationChanged(loc);
}
your method will be called very frequently may be 3-4 times in sec (Did not count how many time). Actually it will be called when ever you location details changed. You are calling method handleLocationChanged(loc); in which you are calling
generateNoteOnSD("GpsTesting", "lattitude is" + lattitude + "\n"
+ " longitude" + longitude);
Method which is creating/opening file in sd card and writing data into it. This can create a problem and you can encounter problem of ANR in the application.
Do not do that. Use a difference of time like 2-3 seconds to write location data into file. Also you are directly writing data not updating it so also keep that in mind.
Hope that helps.

Finally i had got my answer, nothing is wrong in above code just using Myservice.this in place of MainActivity.getContextForService() and increasing time to 0 to 5000 milliseconds , Now its working like charm

Related

save Lat long in database through background service after every 5 minutes intervel

I want to save my current longitude and latitude through backend service or thread in database after every 5 minutes interval. Then I retrive all the lat long from db and draw its location path.
How can I do this in android? This is my code:
public class MyTestService extends IntentService {
Intent i;
TimerTask hourlyTask;
Timer timer;
Location location;
// Must create a default constructor
public MyTestService() {
// Used to name the worker thread, important only for debugging.
super("test-service");
}
#Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
// If a Context object is needed, call getApplicationContext() here.
onHandleIntent(i);
}
#Override
protected void onHandleIntent(Intent intent) {
timer = new Timer();
hourlyTask = new TimerTask() {
#Override
public void run () {
onHandleIntent(i);
}
};
// schedule the task to run starting now and then every hour...
timer.schedule(hourlyTask, 0l, 1000*5*60); // 1000*10*60 every 10 minut
SQLiteDatabase db;
db = openOrCreateDatabase("Temp.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
try {
final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
+ "ID INTEGER primary key AUTOINCREMENT,"
+ "DESCRIPTION TEXT,"
+ "expirydate DATETIME,"
+ "AMOUNT TEXT,"
+ "TRNS TEXT," + "isdefault TEXT);";
db.execSQL(CREATE_TABLE_CONTAIN);
Toast.makeText(getApplicationContext(), "table created ", Toast.LENGTH_LONG).show();
String sql =
"INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('farhan','03/04/2005','5000','ali','y')";
db.execSQL(sql);
Toast.makeText(getApplicationContext(), "inserted", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "ERROR " + e.toString(), Toast.LENGTH_LONG).show();
}
}
implement two interfaces : ConnectionCallbacks, OnConnectionFailedListener with your activity and do the following to get lat and long hope it helps .
String lat="";
String longi="";
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
LocationListener mLocationListener;
// method to create connection with GoogleApiClinet
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
//method to request user to on location
public void forLocation(){
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("GPS not enabled");
dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
HomeActivity.this.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
// inside onCreate method
forLocation();
buildGoogleApiClient();
if(mGoogleApiClient!= null){
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Not connected...", Toast.LENGTH_SHORT).show();
}
//override two methods in your activity
#Override
public void onConnected(Bundle arg0) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//System.out.println("Latitude--------------------------------->: "+ String.valueOf(mLastLocation.getLatitude())+"Longitude: "+
String.valueOf(mLastLocation.getLongitude());
lat=String.valueOf(mLastLocation.getLatitude());
longi=String.valueOf(mLastLocation.getLongitude());
}
}
#Override
public void onConnectionSuspended(int arg0) {
Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show();
}
// user ScheduledThreadPoolExecutor to repeatedly insert data into database
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
// call database insertion service here
}
}, 0, 10, TimeUnit.MINUTES);
// another way is using alarm manager visit documentation link below
Alarm Manager documentation

How to get location of android device by its android id

I am new in android and recently start learning about Android and I am trying to get location of any android device by its unique android id. By that I can track the approx or exact location either by GPS or network provider. In detail I mean to say that whenever i enter any Android id in my app i can get device location in my application. Thanks for your kind help.
Finally I am able to do with this code:
public class MyService extends Service implements LocationListener{
String GPS_FILTER = "";
Thread triggerService;
LocationListener locationListener;
LocationManager lm;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meter
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000 * 60 * 3; // 1 minute
protected LocationManager locationManager;
boolean isRunning = true;
Calendar cur_cal = Calendar.getInstance();
Location location;
double latitude; // latitude
double longitude;
UserFunctions userFunction;
private JSONObject json;
private AlertDialogManager alert = new AlertDialogManager();
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_FLAG = "flag";
String android_id ;
String userName;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(),
0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
if (getAccount() != null) {
userName = getAccount();
}
GPS_FILTER = "MyGPSLocation";
// locationManager = (LocationManager)
// getSystemService(Context.LOCATION_SERVICE);
// locationManager.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
// MINIMUM_TIME_BETWEEN_UPDATES,
// MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
// new MyLocationListener());
cur_cal.setTimeInMillis(System.currentTimeMillis());
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(),
60 * 1000*3, pintent);
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
//turnGPSOn();
/*Toast.makeText(getApplicationContext(), "Hello1", Toast.LENGTH_LONG)
.show();*/
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
/*Toast.makeText(getApplicationContext(), latitude + ", ll" + longitude, Toast.LENGTH_LONG)
.show();*/
userFunction = new UserFunctions();
new YourAsyncTaskLogin().execute();
}
}
location =locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES, 1.0f, locationListener);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// removeGpsListener();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
// private void removeGpsListener(){
// try{
// lm.removeUpdates(locationManager);
// }
// catch(Exception ex){
// System.out.println("Exception in GPSService --- "+ex);
// }
// }
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
postdata(location.getLatitude(), location.getLongitude());
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
/*Toast.makeText(MyService.this, message, Toast.LENGTH_LONG).show();
turnGPSOff();*/
}
private void postdata(double latitude, double longitude) {
// TODO Auto-generated method stub
/*Toast.makeText(getApplicationContext(),
latitude + ", " + longitude, Toast.LENGTH_LONG).show();*/
}
public void onStatusChanged(String s, int i, Bundle b) {
// Toast.makeText(MyService.this, "Provider status changed",
// Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
// Toast.makeText(MyService.this,
// "Provider disabled by the user. GPS turned off",
// Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
// Toast.makeText(MyService.this,
// "Provider enabled by the user. GPS turned on",
// Toast.LENGTH_LONG).show();
}
}
public void turnGPSOn() {
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);
}
}
// automatic turn off the gps
public void turnGPSOff() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
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);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
class YourAsyncTaskLogin extends AsyncTask<Void, Void, Void> {
//private ProgressDialog _ProgressDialog;
#Override
protected void onPreExecute() {
// show your dialog here
/*_ProgressDialog = ProgressDialog.show(getApplicationContext(), "",
"Loading", true);*/
}
#Override
protected Void doInBackground(Void... params) {
json = userFunction.sendLocations(android_id, userName,latitude+"", longitude+"");
return null;
}
protected void onPostExecute(Void result) {
try {
Log.e("Key_Success:",
json.getString(KEY_SUCCESS));
if (json.getString(KEY_SUCCESS) != null) {
// loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
} else {
// Error in login
// loginErrorMsg.setText("Incorrect username/password");
//_ProgressDialog.cancel();
}
} else {
// Error in login
// loginErrorMsg.setText("Incorrect username/password");
//_ProgressDialog.cancel();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", e.getMessage());
}
//_ProgressDialog.dismiss();
}
}
public String getAccount() {
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccountsByType("com.google");
if (list.length != 0) {
String email = list[0].name;
return email;
} else {
return null;
}
}
}
if you want to get location of any device who has your app in their mobile , you can get it ,
firstly in your app you can upload locations to your server with memberid(you can set it , unique for every device) for every x time(you can set it how many times you update the location).
And then you can check your db on your server which device in where.
(my advice you can use webservice to update db on your server)

How to run android application in background [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to run application in background in android?
i am doing project using location manager if my location latitude and longitude equal to the same which is in database mobile profile should go to silent mode.so i need to keep on update my location using location manager.i did it .but if i close my app it's not working.
but my app should be working even though i close my app.i tried with async task its working when i close the app but after i switch to loud mode manually it's not changing to silent.i should also get notified when my app runs n background..please help.tks in advance
here is my code
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
double lat,lng;
Location location;
AudioManager mobilemode ;
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
mobilemode = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
flag = displayGpsStatus();
if (flag) {
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
if((lat==12.905478)&&(lng==80.093358))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show();
}
else if ((lat==12.90080625)&&(lng==80.09210655))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getBaseContext(),"SILENT profile activated !",Toast.LENGTH_SHORT).show();
//notification.setLatestEventInfo(ShowLocationActivity.this, "changed to silent mode", "because u r in office", pendingIntent);
// notificationManager.notify(i, notification);
}
else
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getBaseContext(),"LOUD profile activated !",Toast.LENGTH_SHORT).show();
}
}
else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.location, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent( ShowLocationActivity.this,SetPreference.class);
startActivityForResult(intent, 0);
checkPref();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkPref(){
SharedPreferences myPref
= PreferenceManager.getDefaultSharedPreferences(ShowLocationActivity.this);
String _pref =
"Option 1: " + myPref.getBoolean("pref_opt1", true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
checkPref();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void rrr(View v)
{
DownloadTask n= new DownloadTask();
n.doInBackground();
}
public void onDestroy()
{
super.onDestroy();
Log.v("hhh","on destroy");
DownloadTask n= new DownloadTask();
n.doInBackground();
}
public Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public class DownloadTask extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
Log.v("hhh","back");
onCreate(null);
// onLocationChanged(location);
/*
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
if((lat==12.905478)&&(lng==80.093358))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show();
}
else if ((lat==12.90080625)&&(lng==80.09210655))
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getBaseContext(),"SILENT profile activated !",Toast.LENGTH_SHORT).show();
//notification.setLatestEventInfo(ShowLocationActivity.this, "changed to silent mode", "because u r in office", pendingIntent);
// notificationManager.notify(i, notification);
}
else
{
mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getBaseContext(),"LOUD profile activated !",Toast.LENGTH_SHORT).show();
}
}
else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
// TODO Auto-generated method stub
*/
return null;
}
}
}
You have coded in Activity, I suggest you to changed it to Android Service. A Service is a component which runs in the background, without interacting with the user.
Have a look at Vogella's Service Example.
Just Convert your Activity code into Android Service and it will work in background without any GUI.

getting force close application if GPS disabled

I have application to get location from gps
but if GPS disabled my application getting force close
in emulator it's fine not error,but if run in device it's force close
how can i do this??
this is my code:
public class Track extends Activity implements LocationListener{
String curTime;
double lat;
double lng;
double alt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String provider = locationManager.getBestProvider(criteria, true);
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
updateWithNewLocation(null);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
db.isOpen();
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
//db.close();
}
}, 10*60*1000, 10*60*1000);
locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
locationListener);
PackageManager manager = this.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(this.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this,
"PackageName = " + info.packageName + "\nVersionCode = "
+ info.versionCode + "\nVersionName = "
+ info.versionName + "\nPermissions = "+info.permissions, Toast.LENGTH_SHORT).show();
System.out.println("PackageName = " + info.packageName + "\nVersionCode = "
+ info.versionCode + "\nVersionName = "
+ info.versionName + "\nPermissions = "+info.permissions);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
public void updateWithNewLocation(Location location) {
if (location != null) {
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
long time = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
curTime = df.format(time);
lat = location.getLatitude();
lng = location.getLongitude();
alt = location.getAltitude();
System.out.println(lat);
System.out.println(lng);
System.out.println(alt);
/*db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();*/
/*Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run(){
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();
}
}, 10*60*1000, 10*60*1000);*/
}
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
please give me a solution..thank you for feed back :)
If you want to turn on GPS enabled automatically in your app, I'm afraid there is no way other than prompt the user.
You can achieve that easily with modifying onProviderDisabled() method in your LocationListener. The idea is to open a dialog asking user to turn on GPS:
public void onProviderDisabled(String arg0)
{
showDialog(CHOICE_GPS_ENABLE);
}
add in your activity:
protected final static int CHOICE_GPS_ENABLE = 1; //or any other number
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
switch (id)
{
case CHOICE_GPS_ENABLE:
dialog = createGPSEnableDialog();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
protected Dialog createGPSEnableDialog()
{
Dialog toReturnGPS;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You don't have GPS enabled. Go to Settings and enable GPS?");
builder.setTitle("GPS failed");
builder.setPositiveButton("Yes, enable GPS",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton("No, quit application",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
onDestroy();
}
});
toReturnGPS = builder.create();
return toReturnGPS;
}
Hope it helps.
i want GPS turn on automatically if my application running
how can i do this??
I don't think you can do anything beyond prompt the user to turn it on. So Im afraid you are going to be unable to make your application work how you'd like.
use
Location locationtest;
public void onLocationChanged(Location location) {
locationtest=location;
updateWithNewLocation(locationtest);
}
public void onProviderDisabled(String provider){
locationtest= null;
updateWithNewLocation(locationtest);
}
instead of
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}

Why is this code to get the location via GPS not working?

I am not able to get the location even though the GPS is enabled and all location managers and listeners are set correctly. Here's what I have so far:
public class GpsTest extends Activity {
private TextView text;
private LocationManager manager;
private LocationListener listener;
private Location myLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.textView1);
try
{
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //"gps"
text.setText(("Lat: " + myLocation.getLatitude()
+ "\nLLong: " + myLocation.getLongitude()));
listener = new MyLocationListener();
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
1,
listener);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is enable. ", Toast.LENGTH_SHORT).show();
}
else createGpsDisabledAlert();
}catch(Exception ex)
{
createGpsDisabledAlert();
}
}
public void onclicklistener(View v){
try
{
text.setText(("Lat: " + myLocation.getLatitude()
+ "\nLLong: " + myLocation.getLongitude()));
}catch(Exception ex)
{
Toast.makeText(this, "Error while getting locations. "+ex.toString(), Toast.LENGTH_SHORT).show();
}
}
private void createGpsDisabledAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
showGpsOptions();
}
});
builder.setNegativeButton("No Thanks",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions(){
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
text.setText(("Lat: " + location.getLatitude()
+ "\nLLong: " + location.getLongitude()));
}
Toast.makeText(GpsTest.this, ""+location, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
}
You must to use a thread with his run() method like this (Is in spanish, i hope this not a problem for you)
#Override
public void run() {
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Looper.prepare();
mToast.Make(getContext(),"GPS",0);
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
} else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
Looper.prepare();
mToast.Make(getContext(),"Triangulacion",0);
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
}else{
mToast.Make(context,"No se encuentra seƱal se procede a mandar un mensaje normal",0);
Looper.prepare();
handlerNormal.sendEmptyMessage(0);
Looper.loop();
Looper.myLooper().quit();
}
}
Are you testing on emulator or real device? If you are testing on emulator, check this http://www.javacodegeeks.com/2010/09/android-location-based-services.html and read about DDMS section for location controls. You need to provide some dummy location data for first occurrence and after that it will grab your current location.

Categories

Resources