Hai am trying to get the gps location using BroadCast Receiver.its working fine,But i want to get the location every half hour once.i used **MINIMUM_TIME_BETWEEN_UPDATES ** 30mts .i got when latitude and longitude value changed
update
public class MainActivity extends Activity implements LocationListener {
final DBAdapter1 db=new DBAdapter1(this);
private ConnectivityReceiver receiver = null;
private TextView txtNetworkInfo ;
private static TextView latituteField;
private static TextView longitudeField;
private LocationManager locationManager;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
private static final String HostUrl =" http://xxx/Service.svc";
// private static final String HostUrl =" http://yyyService.svc";
private static final String NAMESPACE = "http://tempuri.org/";
private HttpTransportSE httpTransport = new HttpTransportSE(HostUrl);
private String provider;
private SoapObject request=null;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1800000; // in Milliseconds
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
Log.i("ConnTest",locationManager.toString());
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
float lat = (float) (location.getLatitude());
float lng = (float) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("provider not available");
longitudeField.setText("provider not available");
}
txtNetworkInfo = (TextView)findViewById(R.id.txtNetworkInfo);
receiver = new ConnectivityReceiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onResume() {
super.onResume();
//locationManager.requestLocationUpdates(provider,1000, 1, this);
locationManager.requestLocationUpdates(
provider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
this
);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float lat = (float) (location.getLatitude());
float lng = (float) (location.getLongitude());
longitudeField.setText(String.valueOf(lng));
latituteField.setText(String.valueOf(lat));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#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
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
protected void Display(Cursor c) {
Toast.makeText(this, "rowid: " + c.getString(0) + "\n" +
"Latitude: " + c.getString(1) + "\n" + "Longitude: " + c.getString(2) + "\n" +
Toast.LENGTH_LONG, 0).show();
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
private String getNetworkStateString(NetworkInfo.State state){
String stateString = "Unknown";
switch(state)
{
case CONNECTED: stateString = "Connected"; break;
case CONNECTING: stateString = "Connecting"; break;
case DISCONNECTED: stateString = "Disconnected"; break;
case DISCONNECTING: stateString = "Disconnecting"; break;
case SUSPENDED: stateString = "Suspended"; break;
default: stateString = "Unknown"; break;
}
return stateString;
}
private class ConnectivityReceiver extends BroadcastReceiver{
private Timer mTimer;
private TimerTask mTimerTask;
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(null != info)
{
String state = getNetworkStateString(info.getState());
if(state.equals("Connected")){
try{
mTimer = new Timer();
mTimer.scheduleAtFixedRate(mTimerTask,1000,1800000);
mTimerTask = new TimerTask() {
#Override
public void run() {
SoapPrimitive response=null;
final String methodname="InsertAllGPSInformation";
request = new SoapObject(NAMESPACE,methodname);
envelope.dotNet = true;
request.addProperty("Longitude",longitudeField.getText().toString());
request.addProperty("Latitude",latituteField.getText().toString());
request.addProperty("Date",newtime);
envelope.setOutputSoapObject(request);
String result = null;
try
{
httpTransport.call(NAMESPACE+"IService/"+methodname, envelope);
response = ( SoapPrimitive )envelope.getResponse();
result=response.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), "Your Net Connected or Not Login to Net"+"", Toast.LENGTH_LONG).show();
Log.e("Upload Picture Error:",e.getMessage());
}
}
};
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage()+"", Toast.LENGTH_LONG).show();
Log.e("Upload Picture Error:",e.getMessage());
}
I guess the question is "why do I get more updates than once every 30 minutes?":
Then the answer would be: "the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.".
See http://developer.android.com/reference/android/location/LocationManager.html
Alternatively you could use a Handler or trigger an alarm every 30' and request a single location update when the alarm fires. Starting with API 9 there is a requestSingleUpdate().
Use Alarm Manager. Because your timer can die. But Alarm will wake your app. Try this working code: It wakes CPU every 10 minutes and shows notification.
Add to Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name="Alarm"></receiver>
...
Code:
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Related
I'm implementing an application which need to send a location to GCM every 15 minutes. I implemented an AlarmManager which will be called every 15 minute.
Here is my class of my alarmmanager
public class LocationAlarmManager {
Context mContext = null;
public LocationAlarmManager (Context context) {
mContext = context;
}
private AlarmManager alarmManager;
private Intent gpsTrackerIntent;
private PendingIntent pendingIntent;
private static final String TAG = "LocationAlarmManager";
public void startAlarmManager() {
Log.d(TAG, "startAlarmManager");
alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
gpsTrackerIntent = new Intent(mContext, GpsTrackerAlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(mContext, 0, gpsTrackerIntent, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
15 * 60000, // 60000 = 1 minute
pendingIntent);
}
public void cancelAlarmManager() {
Log.d(TAG, "cancelAlarmManager");
Intent gpsTrackerIntent = new Intent(mContext, GpsTrackerAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, gpsTrackerIntent, 0);
AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
That one calls GpsTrackerAlarmReceiver
// make sure we use a WakefulBroadcastReceiver so that we acquire a partial wakelock
public class GpsTrackerAlarmReceiver extends WakefulBroadcastReceiver {
private static final String TAG = "GpsTrackerAlarmReceiver";
#Override
public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, SmartLocationService.class));
}
}
For handling my location I implemented the following in my SmartLocationService.
public class SmartLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "SmartLocationService";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private LocationClient locationClient;
public LocationManager locationManager;
Context context;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
public Location previousBestLocation;
private double mLastLatitudeLocation = 0;
private double mLastLongitudeLocation = 0;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationClient = new LocationClient(this,this,this);
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationDataToWebsite(Location loc) {
MessageHandler messageHandler = new MessageHandler(SmartLocationService.this);
messageHandler.sendLocationMessage(loc); //send location to GCM
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
sendLocationDataToWebsite(location);
}
}
private void stopLocationUpdates() {
if (locationClient != null && locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
locationClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
context = getApplicationContext();
Log.d(TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(900000); // milliseconds
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationClient.requestLocationUpdates(locationRequest, this);
}
/**
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
Log.e(TAG, "onDisconnected");
stopLocationUpdates();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
}
This works, but my locationservice get called more then once in my timeslot of 15 minutes. Anyone know why? Is this a good way to use less battery power (GPS)?
Thanks
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)
i have problem with my Android application.I need an application that will get in background GPS location while open another application.application run in background but i want to also get GPS location in background.
create start and stop button for get gps location it work properly but when click on home button gps stop to gettting location
Here is My code..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
/* get TextView to display the GPS data */
txtLat = (TextView) findViewById(R.id.textview1);
/* the location manager is the most vital part it allows access
* to location and GPS status services */
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER ,10000,10, this);
// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000L, 0, this);
btnShow = (Button) findViewById(R.id.btnstart);
btnStop = (Button) findViewById(R.id.btnstop);
btnShow.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), "Trip Start.", Toast.LENGTH_SHORT).show();
txtLat.setVisibility(View.VISIBLE);
onResume();
btnShow.setEnabled(false);
btnStop.setEnabled(true);
}
});
Button btnstop = (Button) findViewById(R.id.btnstop);
btnstop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onPause();
Toast.makeText(getBaseContext(), "Trip Ended.", Toast.LENGTH_SHORT).show();
btnShow.setEnabled(true);
btnStop.setEnabled(false);
}
});
}
public void onLocationChanged(Location location) {
if (location == null) {
Toast.makeText(getApplicationContext(),"Searching for your location.", Toast.LENGTH_SHORT).show();
locationManager.requestLocationUpdates(provider, 10000, 10,locationListener);
onLocationChanged(location);
}
else
{
double cell_lat=location.getLatitude();
double cell_long=location.getLongitude();
double altitude=location.getAltitude();
double accuracy=location.getAccuracy();
String status="true";
sb = new StringBuilder(512);
noOfFixes++;
/* display some of the data in the TextView */
sb.append("Tracking: ");
sb.append(noOfFixes);
sb.append('\n');
sb.append('\n');
sb.append("Londitude: ");
sb.append(location.getLongitude());
sb.append('\n');
sb.append("Latitude: ");
sb.append(location.getLatitude());
sb.append('\n');
sb.append("Altitiude: ");
sb.append(location.getAltitude());
sb.append('\n');
sb.append("Accuracy: ");
sb.append(location.getAccuracy());
sb.append("ft");
sb.append('\n');
txtLat.setText(sb.toString());
}
public void onProviderDisabled(String provider) {
/* this is called if/when the GPS is disabled in settings */
Log.v(tag, "Disabled");
/* bring up the GPS settings */
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String provider) {
Log.v(tag, "Enabled");
Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status alters */
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v(tag, "Status Changed: Out of Service");
Toast`enter code here`.makeText(this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v(tag, "Status Changed: Temporarily Unavailable");
Toast.makeText(this, "Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v(tag, "Status Changed: Available");
Toast.makeText(this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
#Override
protected void onResume() {
/*
* onResume is is always called after onStart, even if the app hasn't been
* paused
*
* add location listener and request updates every 1000ms or 10m
*/
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this);
super.onResume();
}
#Override
protected void onPause() {
/* GPS, as it turns out, consumes battery like crazy */
locationManager.removeUp`enter code here`dates(this);
super.onPause();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
System.out.println("KEYCODE_HOME");
Toast.makeText(getBaseContext(), "Home Button.", Toast.LENGTH_SHORT).show();
this.moveTaskToBack(true);
//showDialog("'HOME'");
return true;
}
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
System.out.println("KEYCODE_BACK");
finish();
showDialog("'BACK'");
return true;
}
if ((keyCode == KeyEvent.KEYCODE_MENU)) {
System.out.println("KEYCODE_MENU");
//showDialog("'MENU'");
return true;
}
return false;
}
void showDialog(String the_key){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("GPS.");
alert.show();
}
I found this code somewhere It worked for me LINK, I had modified the code according to my requirement, give it a try.
It saves data in the database from the background service, you just need to start the service from an activity, NOTE: it will save in Database only if the distance of first location is more than the given minimum distance.
public class BackgroundLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "BackgroundLocationService";
IBinder mBinder = new LocalBinder();
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
private double previousLatitude = 0;
private double previousLongitude = 0;
private SharedPreferences stopLocatinServicePreferance;
private float[] distance;
// public static boolean isStopSelf = false;
public class LocalBinder extends Binder {
public BackgroundLocationService getServerInstance() {
return BackgroundLocationService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
mInProgress = false;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);
servicesAvailable = servicesConnected();
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (!servicesAvailable || mLocationClient.isConnected() || mInProgress)
return START_STICKY;
setUpLocationClientIfNeeded();
if (!mLocationClient.isConnected() || !mLocationClient.isConnecting()
&& !mInProgress) {
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Started", Constants.LOG_FILE);
mInProgress = true;
mLocationClient.connect();
}
return START_STICKY;
}
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null)
mLocationClient = new LocationClient(this, this, this);
}
// Define the callback method that receives location updates
#Override
public void onLocationChanged(Location location) {
// Report to the UI that the location was updated
String msg = Double.toString(location.getLatitude()) + ","
+ Double.toString(location.getLongitude());
Log.d("debug", msg);
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String timeStamp = s.format(new Date());
System.out.println("TimeStamp ddMMyyyyhhmmss =" + timeStamp);
if (isDistanceAccountable(location.getLatitude(),
location.getLongitude(), previousLatitude, previousLongitude)) {
DatabaseHelper dbm = DatabaseHelper
.getInstance(getApplicationContext());
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.KEY_LATLONG, location.getLatitude() + "#"
+ location.getLongitude());
cv.put(DatabaseHelper.KEY_TIMESTAMP, timeStamp);
cv.put(DatabaseHelper.KEY_STATUS, "0");
cv.put(DatabaseHelper.KEY_USER_ID, "");
dbm.insert(DatabaseHelper.TABLE_TRACKINFO_TABLE, cv);
// }
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
appendLog(msg, Constants.LOCATION_FILE);
}
previousLatitude = location.getLatitude();
previousLongitude = location.getLongitude();
stopLocatinServicePreferance = getSharedPreferences("SERVICE_PREF", 0);
boolean check = stopLocatinServicePreferance.getBoolean("isStop", true);
Log.e(TAG, "isStop?" + check);
if (check) {
Log.e(TAG, "is self stoping ");
if (mLocationClient != null) {
mLocationClient.removeLocationUpdates(this);
// Destroy the current location client
mLocationClient = null;
}
this.stopSelf();
}
}
/**
* Returns true if distance is grater than MINIMUM_DISTANCE_ACCOUNTABLE
* NOTE: returns true if there is no previousLatitude,previousLongitude, it
* means this is first time it needs to save the data
*
* #param currentLatitude
* #param currentLongitude
* #param previousLatitude
* #param previousLongitude
* #return
*/
private boolean isDistanceAccountable(double currentLatitude,
double currentLongitude, double previousLatitude,
double previousLongitude) {
distance = new float[1];
if (previousLatitude > 0 && previousLongitude > 0) {
Location.distanceBetween(currentLatitude, currentLongitude,
previousLatitude, previousLongitude, distance);
Log.v(TAG + " > isDistanceAccountable()", "previousLatitude = "
+ previousLatitude + "previousLongitude = "
+ previousLongitude + " currentLatitude = "
+ currentLatitude + " , currentLongitude = "
+ currentLongitude);
} else {
Log.v(TAG + " > isDistanceAccountable()", "previousLatitude = "
+ previousLatitude + "previousLongitude = "
+ previousLongitude);
return true;
}
if (distance[0] > Constants.MINIMUM_DISTANCE_ACCOUNTABLE) {
Log.v(TAG + " > isDistanceAccountable()", "Distance = "
+ distance[0] + "return true");
return true;
} else {
Log.v(TAG + " > isDistanceAccountable()", "Distance = "
+ distance[0] + "return false");
return false;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.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(logFile,
true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDestroy() {
try {
// Turn off the request flag
mInProgress = false;
if (servicesAvailable && mLocationClient != null) {
mLocationClient.removeLocationUpdates(this);
// Destroy the current location client
mLocationClient = null;
}
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Stopped", Constants.LOG_FILE);
} catch (Exception e) {
Log.e(TAG + " > onDestroy()", e.toString());
}
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
mLocationClient.requestLocationUpdates(mLocationRequest, this);
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Connected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
#Override
public void onDisconnected() {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mLocationClient = null;
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Disconnected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
}
Here is the supporting class.
public final class Constants {
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 100;
// Update frequency in seconds
private static final int UPDATE_INTERVAL_IN_SECONDS = 10;
// Update frequency in milliseconds
public static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 10;
// A fast frequency ceiling in milliseconds
public static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND
* FASTEST_INTERVAL_IN_SECONDS;
// Stores the lat / long pairs in a text file
public static final String LOCATION_FILE = "sdcard/location.txt";
// Stores the connect / disconnect data in a text file
public static final String LOG_FILE = "sdcard/log.txt";
// Minimum accountable distance in meters
public static final float MINIMUM_DISTANCE_ACCOUNTABLE = 50;
/**
* Suppress default constructor for noninstantiability
*/
private Constants() {
throw new AssertionError();
}
}
My app is a tracker app, that uses GPS. At every 15 minutes, it finds current location of user. For this, I had used AlarmManager. I am getting The current location through a background service, which is scheduled to run at every 15 minutes. This service will be started by the broadcast receiver upon alarm. But, the problem is alarm fires up before time, i.e. once service started and finished its work, service was supposed to be called after 15 minutes. But, it is getting called at interval of 2-3 minutes.
Activity code
AlarmManager AlmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Sender = PendingIntent.getBroadcast(GpsTrackActivity.this, 0,
AlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlmMgr.setRepeating(AlarmManager.RTC_WAKEUP, 0, 15 * 60 * 1000,
Sender);
BroadcastReceiver
public class StartServiceReceiver extends BroadcastReceiver
{
private static final String TAG = "StartServiceReceiver";
#Override
public void onReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context, MyLocationService.class);
context.startService(serviceIntent);
Log.v(TAG, "onReceive called");
}
}
Service Class
public class MyLocationService extends Service implements
OnLocationReceivedListener {
private LocationManager manager;
private Location location = null;
PowerManager powerManager;
private WakeLock wakeLock;
private String city, time, udid;
private String country;
GPSLocationListener mGPSLocationListener;
NetworkLocationListener mNetworkLocationListener;
private static final int MAX_ATTEMPTS = 250;
private static String TAG = "MyLocationService";
LocTimerTask mTimerTask;
int mSattelites;
Timer myLocTimer;
int i = 0;
boolean isGPS;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand called");
getCurrentLocation();
time = getCurrentTime();
udid = getDeviceId();
return 1;
}
#Override
public void onCreate() {
Log.v(TAG, "onCreate called");
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"mywakelock");
mGPSLocationListener = new GPSLocationListener();
mNetworkLocationListener = new NetworkLocationListener();
wakeLock.acquire();
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public String getCurrentTime() {
String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.getDefault()).format(new Date());
return currentTime;
}
public String getDeviceId() {
TelephonyManager tm = (TelephonyManager) MyLocationService.this
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}
public void getCurrentLocation() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.addGpsStatusListener(mGPSStatusListener);
mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L,
50.0f, mGPSLocationListener);
} else {
turnGPSOn();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L,
50.0f, mGPSLocationListener);
}
myLocTimer = new Timer("LocationRunner", true);
myLocTimer.schedule(mTimerTask, 0, 1000);
}
public String getLong(Location loc) {
String longi = null;
if (loc != null) {
longi = Double.toString(loc.getLongitude());
}
return longi;
}
public String getLat(Location loc) {
String lat = null;
if (loc != null) {
lat = Double.toString(loc.getLatitude());
}
return lat;
}
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location argLocation) {
location = argLocation;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class LocTimerTask extends TimerTask {
String provider;
public LocTimerTask(String provider) {
this.provider = provider;
}
final Handler mHandler = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
#Override
public void run() {
i++;
Log.v(TAG, "Timer Task run " + i);
location = manager.getLastKnownLocation(provider);
if (location != null) {
Log.v(TAG, "in timer task run in if location not null");
isGPS = true;
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
} else {
Log.v(TAG, "in timer task run in else location null");
isGPS = false;
if (location == null && i == MAX_ATTEMPTS) {
Log.v(TAG, "if 1 max attempts done");
turnGPSOff();
location = manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.v(TAG,
"if 1 max attempts done Location from network not null");
Log.v(TAG,
"if 1 max attempts done Location from network not null coordinates not null");
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
i = 0;
return;
} else {
i = 0;
return;
}
} else {
return;
}
}
}
};
public void run() {
mHandler.post(r);
}
}
private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() {
#Override
public synchronized void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.v(TAG, "GPS SAtellitestatus");
GpsStatus status = manager.getGpsStatus(null);
mSattelites = 0;
Iterable<GpsSatellite> list = status.getSatellites();
for (GpsSatellite satellite : list) {
if (satellite.usedInFix()) {
mSattelites++;
}
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast.makeText(getApplicationContext(), "Got First Fix",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STARTED:
Toast.makeText(getApplicationContext(), "GPS Event Started",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
Toast.makeText(getApplicationContext(), "GPS Event Stopped",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
};
public void onDestroy() {
super.onDestroy();
if (myLocTimer != null) {
myLocTimer.cancel();
myLocTimer.purge();
}
if (mTimerTask != null) {
if (mTimerTask.r != null) {
mTimerTask.mHandler.removeCallbacks(mTimerTask.r);
}
}
if (manager != null) {
if (mGPSLocationListener != null) {
manager.removeUpdates(mGPSLocationListener);
}
if (mNetworkLocationListener != null) {
manager.removeUpdates(mNetworkLocationListener);
}
if (mGPSStatusListener != null) {
manager.removeGpsStatusListener(mGPSStatusListener);
}
}
Toast.makeText(getApplicationContext(), "Service onDestroy called",
Toast.LENGTH_LONG).show();
}
#Override
public void onLocationReceived(Location mLoc) {
String lat = getLat(mLoc);
String lon = getLong(mLoc);
if (NetworkConnection.isOnline(getApplicationContext())) {
new SendDataAsynctask(lat, lon, "", time, udid, city, country,
wakeLock).execute();
Log.v(TAG, "net available");
} else {
Toast.makeText(getApplicationContext(), "Network unavailable",
Toast.LENGTH_LONG).show();
Log.v(TAG, "net unavailable");
}
}
}
I have a doubt, does AlarmManager gets affected by Timer or TimerTask. I am asking this because within my service I had used Timer, since it takes time for GPS to find first fix.
Hai i tried to add the timer function in broadcast receiver application to receive the latitude and longitutude in gps .But i got Error.Anybody please kindly rectify my error.
Thanks in advance
i update the error section
public class MainActivity extends Activity implements LocationListener {
final DBAdapter1 db=new DBAdapter1(this);
private ConnectivityReceiver receiver = null;
private TextView txtNetworkInfo ;
private static TextView latituteField;
private static TextView longitudeField;
private LocationManager locationManager;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
private static final String HostUrl =" xxxxx";
// private static final String HostUrl =" yyyy";
private static final String NAMESPACE = "http://tempuri.org/";
private HttpTransportSE httpTransport = new HttpTransportSE(HostUrl);
private String provider;
private SoapObject request=null;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1800000; // in Milliseconds
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
Log.i("ConnTest",locationManager.toString());
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
float lat = (float) (location.getLatitude());
float lng = (float) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("provider not available");
longitudeField.setText("provider not available");
}
txtNetworkInfo = (TextView)findViewById(R.id.txtNetworkInfo);
receiver = new ConnectivityReceiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onResume() {
super.onResume();
//locationManager.requestLocationUpdates(provider,1000, 1, this);
locationManager.requestLocationUpdates(
provider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
this
);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float lat = (float) (location.getLatitude());
float lng = (float) (location.getLongitude());
longitudeField.setText(String.valueOf(lng));
latituteField.setText(String.valueOf(lat));
try {
db.open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long id=db.insert(latituteField.getText().toString(),longitudeField.getText().toString());
if(id>1)
{
Toast.makeText(getBaseContext(),"one record is inserted",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getBaseContext(),"not inserted",Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#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
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
protected void Display(Cursor c) {
Toast.makeText(this, "rowid: " + c.getString(0) + "\n" +
"Latitude: " + c.getString(1) + "\n" + "Longitude: " + c.getString(2) + "\n" +
Toast.LENGTH_LONG, 0).show();
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
private String getNetworkStateString(NetworkInfo.State state){
String stateString = "Unknown";
switch(state)
{
case CONNECTED: stateString = "Connected"; break;
case CONNECTING: stateString = "Connecting"; break;
case DISCONNECTED: stateString = "Disconnected"; break;
case DISCONNECTING: stateString = "Disconnecting"; break;
case SUSPENDED: stateString = "Suspended"; break;
default: stateString = "Unknown"; break;
}
return stateString;
}
private class ConnectivityReceiver extends BroadcastReceiver{
private Timer mTimer;
private TimerTask mTimerTask;
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(null != info)
{
String state = getNetworkStateString(info.getState());
if(state.equals("Connected")){
mTimer = new Timer();
mTimer.scheduleAtFixedRate(mTimerTask,1000,5000);
mTimerTask = new TimerTask() {
#Override
public void run() {
result();
}
};
}
else{
//result();
}
}
}
}
private void result() {
SoapPrimitive response=null;
final String methodname="InsertAllGPSInformation";
request = new SoapObject(NAMESPACE,methodname);
envelope.dotNet = true;
request.addProperty("Longitude",longitudeField.getText().toString());
request.addProperty("Latitude",latituteField.getText().toString());
request.addProperty("Date",newtime);
envelope.setOutputSoapObject(request);
String result = null;
try
{
httpTransport.call(NAMESPACE+"IService/"+methodname, envelope);
response = ( SoapPrimitive )envelope.getResponse();
result=response.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), "Your Net Connected or Not Login to Net"+"", Toast.LENGTH_LONG).show();
Log.e("Upload Picture Error:",e.getMessage());
}
if(result.equals("Saved Successfully")){
Toast.makeText(getBaseContext(), ""+result, Toast.LENGTH_LONG).show();
}
}
}
update
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at android.os.Handler.<init>(Handler.java:121)
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at android.widget.Toast.<init>(Toast.java:68)
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at android.widget.Toast.makeText(Toast.java:231)
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at com.varma.samples.conntest.MainActivity.result(MainActivity.java:240)
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at com.varma.samples.conntest.MainActivity.access$1(MainActivity.java:212)
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at com.varma.samples.conntest.MainActivity$ConnectivityReceiver$1.run(MainActivity.java:199)
01-09 17:13:27.168: ERROR/AndroidRuntime(1983): at java.util.Timer$TimerImpl.run(Timer.java:289)
mTimerTask is null when you call mTimer.scheduleAtFixedRate(mTimerTask,1000,5000); in onRecieve in your ConnectivityReceiver class.
You need to put that line AFTER
mTimerTask = new TimerTask() {
#Override
public void run() {
result();
}
};
So your code will look like this:
mTimerTask = new TimerTask() {
#Override
public void run() {
result();
}
};
mTimer.scheduleAtFixedRate(mTimerTask,1000,5000);
To work this out yourself, if you look at your error message you will see (about half way down):
Caused by: java.lang.NullPointerException
So now you know what has caused your error. Now look down the lines from there until you get to a class & method that you've created. In this case its:
at com.varma.samples.conntest.MainActivity$ConnectivityReceiver.onReceive(MainActivity.java:196)
The class file you're in is com.varma.samples.conntest.MainActivity the class you're in is ConnectivityReveiver and the method you're in is onReceive. If that doesn't help in brackets is the java file and line number where your NullPointer originated from.
Sometimes you might need to trace back a few lines if you're passing a variable through different methods before the NullPointerException is thrown.