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.
Related
I want to send location data to server after a certain time from my android app. I used service and AlarmManager to check location updates continuously in background.
But my problem is that the app sends too many data to server; so that, while I see those location data on map it shows so many data on same location. How can I solve this issue?
Here is the portion of the code where I checked minimum time and distance to check location updates.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 15, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 15, listener);
Is that safe to use minTimeto 30000 milliseconds and minDistance to 15 meters?
If it is ok then how should I filter only one data of a same
location?
If it is not safe then how should I avoid same location data?
I added my LocationListener code below. Here I am checking the best location and sending data to server.
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc)
{
Log.i("**************************************", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc.getLatitude();
loc.getLongitude();
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
mySpeed = loc.getSpeed() * 1.94384449;
myKmph = loc.getSpeed() * 3.6;
myBearing = loc.getBearing();
double flat = loc.getLatitude(); //-32.827141
double flon = loc.getLongitude(); //139.667476
int inlat = (int) flat; //-32
int inlon = (int) flon; //139
float minlat = (float) (flat % 1) * 60; //10.371540000000152
float minlon = (float) (flon % 1) * 60; //
minlat = (minlat < 0) ? -minlat : minlat;
minlon = (minlon < 0) ? -minlon : minlon;
String norther = "N";
String souther = "S";
String easter = "E";
String wester = "W";
String northsouther = "";
String eastwester = "";
if(flat>=0.0) {
northsouther = norther;
}
else {
northsouther = souther;
}
if(flon>=0.0) {
eastwester = easter;
}
else {
eastwester = wester;
}
String text = "...my formate to send data...";
try {
String ip = "XX.XXX.XXX.XXX";
int port = XXXX;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Socket clientSocket = new Socket(ip, port);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(text);
clientSocket.close();
Log.d("LocationService", "Data sent successfully");
} catch (Exception e) {
Log.e("LocationService", "[Error] Either in Sending Data or the callback" + e.toString());
}
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
Please suggest me possible ways to overcome this situation?
Thanks in advance.
You can provide a validation of some kind in this code.Lets say we provide a validation that if the distance moved is more than 15 meters we send the latitude and longitude to the server.You can write your code like this:
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc)
{
Log.i("**************************************", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc1_lat =loc.getLatitude();
loc1_long = loc.getLongitude();
// define double loc2_lat==0 and loc2_long=0 so we initially enter this condition;
if ((loc2_lat == null || loc2_lat == 0.0)
&& (loc2_long == null || loc2_long == 0.0))
{
double loc2_lat = loc1_lat;
double loc2_long = loc1_long;
}
//new piece of code goes here.
Location locationA = new Location("point A");
locationA.setLatitude(loc1_lat);
locationA.setLongitude(loc1_long);
Location locationB = new Location("point B");
locationB.setLatitude(loc2_lat);
locationB.setLongitude(loc2_lat);
//calculate distance between current lat long and future lat long
float calculated_distance = locationA.distanceTo(locationB);
//calculated_distance in meter.
calculated_distance = distance_U_driver / 1000;
//put this validation by yourself in meters.If you want your device to move 15 meter and then send the next coordinate
if(calculated_distance > 15){
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
}
mySpeed = loc.getSpeed() * 1.94384449;
myKmph = loc.getSpeed() * 3.6;
myBearing = loc.getBearing();
double flat = loc.getLatitude(); //-32.827141
double flon = loc.getLongitude(); //139.667476
int inlat = (int) flat; //-32
int inlon = (int) flon; //139
float minlat = (float) (flat % 1) * 60; //10.371540000000152
float minlon = (float) (flon % 1) * 60; //
minlat = (minlat < 0) ? -minlat : minlat;
minlon = (minlon < 0) ? -minlon : minlon;
String norther = "N";
String souther = "S";
String easter = "E";
String wester = "W";
String northsouther = "";
String eastwester = "";
if(flat>=0.0) {
northsouther = norther;
}
else {
northsouther = souther;
}
if(flon>=0.0) {
eastwester = easter;
}
else {
eastwester = wester;
}
String text = "...my formate to send data...";
try {
String ip = "XX.XXX.XXX.XXX";
int port = XXXX;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Socket clientSocket = new Socket(ip, port);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(text);
clientSocket.close();
Log.d("LocationService", "Data sent successfully");
} catch (Exception e) {
Log.e("LocationService", "[Error] Either in Sending Data or the callback" + e.toString());
}
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
I have written a background service to insert latitude , longitude and some other details into my sqlite database based on the time limit set in my AlarmManager.
I am using GoogleApiClient to calculate latitude and longitude , but i am facing some problems.
Problem
When i am travelling outside without net , the latitude and longitude is not getting updated at regular intervals. The data is getting inserted in my sqlite at regular intervals but latitude and longitude remains same even after half an hour though i am travelling some about 10 kms.
I want the latitude and longitude to change while i am travelling like auto update.
I wanted to know if the FusedLocationApi calculates latitude longitude properly even if i am not connected to the internet , if yes then i need some suggestions to improve the code that i have tried.
Code i have tried.
AlarmManagerService.java
public class AlarmManagerService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "AlarmManagerService";
AlarmReceiver alarmReceiver;
DriverDbHelper driverDbHelper;
Handler handler;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 120000; // 2 mins
private static int FATEST_INTERVAL = 60000; // 1 min
private static int DISPLACEMENT = 10; // 10 meters
public Activity activity;
protected String mLastUpdateTime;
String areaName0, areaName1, areaName2, areaName3, fullAreaName,
sessionMobileNo, sessionDriverName, sessionDID, sessiondriverUserId,
date, time, dateTime, doc, trac_transId;
double latitude, longitude;
PowerManager.WakeLock mWakeLock;
SessionManager session;
ConnectionDetector cd;
Boolean isInternet = false;
String sync_no = "No";
String sync_yes = "Yes";
public AlarmManagerService() {
alarmReceiver = new AlarmReceiver();
driverDbHelper = new DriverDbHelper(this);
cd = new ConnectionDetector(this);
}
public void setActivity(Activity activity) {
this.activity = activity;
}
#Override
public void onCreate() {
super.onCreate();
try {
driverDbHelper.open(AlarmManagerService.this);
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Service created", "Alarm Service Created");
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager mgr = (PowerManager)
getSystemService(Context.POWER_SERVICE);
if (this.mWakeLock == null) {
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
}
if (!this.mWakeLock.isHeld()) {
this.mWakeLock.acquire();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
Log.d("Service started", "Alarm Service Started");
handler = new Handler(Looper.myLooper());
handler.post(new Runnable() {
#Override
public void run() {
postDatabaseDetails();
}
});
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service started", "Alarm Service Destroyed");
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
}
private void displayLocation() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
List<Address> addressList = null;
try {
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
addressList = gcd.getFromLocation(mLastLocation.getLatitude(),
mLastLocation.getLongitude(), 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
areaName0 = address.getLocality(); // city name
areaName1 = address.getSubLocality();
areaName2 = address.getAdminArea();// statename
//areaName3 = address.getFeatureName(); plot no
//areaName3 = address.getCountryCode();// IN
areaName3 = address.getThoroughfare();
fullAreaName = areaName3 + "\n" + areaName1 + "\n" +
areaName0 + "," + areaName2;
} else {
Log.i("Location ", "Location null");
}
} catch (IOException e1) {
Log.e("HomePage", "IO Exception in getFromLocation()");
e1.printStackTrace();
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(mLastLocation.getLatitude()) + " , " +
Double.toString(mLastLocation.getLongitude()) +
" passed to address service";
Log.e("HomePage", errorString);
e2.printStackTrace();
}
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
//mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, activity,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i("Google play services", "Device not supported");
activity.finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
*/
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onConnected(Bundle bundle) {
// Once connected with google api, get the location
//displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
if (mLastLocation == null) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
displayLocation();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.d("Location changed ", "Location changed " + mLastLocation);
Log.d("Last updated time", "Last updated location " + mLastUpdateTime);
// Displaying the new location on UI
displayLocation();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
public void postDatabaseDetails() {
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
sessionMobileNo = user.get(SessionManager.KEY_MOBILENO);
sessionDriverName = user.get(SessionManager.KEY_NAME);
sessionDID = user.get(SessionManager.KEY_DEVICEID);
sessiondriverUserId = user.get(SessionManager.KEY_DRIVERUSERID);
Calendar in = Calendar.getInstance();
Date dt = new Date();
in.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss");
date = sdf.format(dt);
time = stf.format(dt);
String timeval = time.toString();
String dateval = date.toString();
dateTime = date.toString() + " " + time.toString();
doc = sessionDID + "" + dateTime;
isInternet = cd.isConnectingToInternet();
if (isInternet) {
long id = driverDbHelper.insertDriverDetails(doc, sessionDID,
sessiondriverUserId, latitude, longitude,
fullAreaName, dateTime, "DEMO", sync_no, dateval, timeval);
postDriverDetails();
Log.d("GPS", "Service started after 2 mins with internet");
} else {
Log.d("Internet status", "No internet available for service");
long id = driverDbHelper.insertDriverDetails(doc, sessionDID,
sessiondriverUserId, latitude, longitude,
"NA", dateTime, "DEMO", sync_no, dateval, timeval);
Log.d("GPS", "Service started after 2 mins without internet");
}
}
I am calling this service from the activity HomePage.java , but from where do i have to call the below code , from onStart() or after setContentView(R.layout.home)?
try {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MINUTE, 2);
AlarmManager am = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(Home_Page.this, AlarmManagerService.class);
PendingIntent pi = PendingIntent.getService(Home_Page.this, 0, i,0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), EXEC_INTERVAL, pi);
} catch (Exception e) {
e.printStackTrace();
}
I hope i can get some suggestions to improve the above service code as i want it to run smoothly in background updating the latitude and longitude at regular intervals.
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!!
i am developing an gps program in that i am getting gps values for every 5 minutes,
and it is working great, but i have to store the values which i get. it has been refreshed for every 5 minutes and i have only one text view so that it deletes the old values when the new one is refreshed.
this is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 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");
} else {
tv.setText("Problem getting location");
}
}
#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;
}
Thank you.
You can store your Textview's value into a file for persistance storage. Study my answer properly, I am adding a file store method in your existing code,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 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 location");
}
}
#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("sdcard/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));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to write following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well you have plenty of persistence options, but in this case the best is using SharedPreferences
No one can say for sure without knowing exactly what you need to do with the saved data. ArrayList is a good option if you need to store it temporarily. You can create a new ArrayList then put the value in there at the same time that you use it in setText(). If you want something permanent then you will probably want to store it in a DB or a file. Check out Storage Options
Also, in this case, a good idea may be to store it in an ArrayList temporarily then use that list to transfer them to a file or DB for permanent storage if that's what you want
Another way to store it temporarily, and possibly save somewhere later would be a HashMap. Maybe something in the form of HashMap<String, HashMap<String, String>>. Since we don't know your exact intentions with the data, examples could be endless but maybe this will give you a good starting point so you can decide what will work best for you then you can find many examples all over SO and the Google for your choice
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);
}
}