I am trying to send users location via sms. I can get the users location but it takes lot time while the smsmanager sends the message with null value of location can somebody see my code or guide me what is wrong here. thanks!
public class MainActivity extends AppCompatActivity {
public Button button;
private LocationManager locationManager;
private LocationListener listener;
private String gpslonla;
private TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getlocation();
sendlocationsms();
}
private void sendlocationsms() {
String phoneNumber = "903399000";
//Location location = new Location("dummyprovider");
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append("http://maps.google.com?q="+gpslonla);
//smsBody.append(location.getLatitude());
//smsBody.append(",");
//smsBody.append(location.getLongitude());
smsManager.sendTextMessage(phoneNumber, null, smsBody.toString(), null, null);
int gravity = Gravity.CENTER; // the position of toast
int xOffset = 0; // horizontal offset from current gravity
int yOffset = 0; // vertical offset from current gravity
Toast toast = Toast.makeText(getApplicationContext(), "Your message has been sent ", Toast.LENGTH_SHORT);
toast.setMargin(50, 50);
toast.setGravity(gravity, xOffset, yOffset);
toast.show();
}
});
}
private void getlocation() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
gpslonla=location.getLongitude() + "," + location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button() {
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
}
}
You must call the sendlocationsms() method when the location is received. Change your onClick method with:
EDITED:
Declare a boolean variable with initial value to false:
boolean needsToSendSms = false;
Then:
#Override
public void onClick(View view) {
needsToSendSms = true;
getlocation();
}
And call it when the location changes with
#Override
public void onLocationChanged(Location location) {
gpslonla=location.getLongitude() + "," + location.getLatitude();
if(needsToSendSms) {
sendlocationsms();
needsToSendSms = false;
}
}
Adding the boolean variable makes to only send one sms per click.
I hope this helps.
Related
I have a button and when I press it it show me in 2 TextView my location(in textview3 the X, and textview21 the Y) and I want to listen my location with text to speech. The problem is: The text to speech is not working right and it say my location in loop. It's read right the textviews but the text to speech say/repeats the Location all the time. It will stop the repeat when I close the program. I don't know how to fix it.
The code in MainActivity2 for Location
ImageButtonLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity2.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity2.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQ_LOC_CODE);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MainActivity2.this);
//locationManager.removeUpdates(MainActivity.this);
}
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
// 0, 0, MainActivity.this);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER., 0, 0 , MainActivity.this);
}
});
}
//energopoietai apo to kleisimou tou dangerous permissions
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_LOC_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MainActivity2.this);
}
}
#Override
public void onLocationChanged(#NonNull Location location) {
//sintetagmenes sto text
x=location.getLatitude();
y=location.getLongitude();
textView3.setText(String.format("Your current location is:X=%.2f",x));
textView21.setText(String.format(" and Y=%.2f",y));
textspeech.speak("Your current location is:"+"X="+String.format("%.2f",x)+","+"\n"+"Y="+String.format("%.2f",y));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(#NonNull String provider) {
}
#Override
public void onProviderDisabled(#NonNull String provider) {
}
And the activity:textspeech
public class textspeech {
private TextToSpeech tts;
TextToSpeech.OnInitListener initListener=new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
tts.setLanguage(Locale.US);
}
}
};
//prepei na ftiaksume constructor moni mas gt h mixani omilias dn
// mporei na energopoithi moni ths h klasi prepei na energopoiithoi apo contex
public textspeech(Context context){
tts=new TextToSpeech(context, initListener);
}
//methodos gia na tn kalume
public void speak(String message){
tts.speak(message,TextToSpeech.QUEUE_ADD, null,null);
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, MainActivity2.this);
As I understand it, you want to wait for a while before reading the second address after the first address is read, right? If you want to do this, you can read the first address and then wait for a while with the Handler and then start reading the second address.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
start Voice 2
}
}, 1000);
I have an app which obtains the users location and sends it to my Firebase Database which has a list of locations closest to the user. The location radius has been set to less than 50km(50000m). if there are no locations within that radius, I want an alert dialog to appear saying that there are no locations available. The locations will be updated as the app runs. The alert dialog should be shown every time the user tries to access the locations within the set radius. Can someone help me out on how to go about doing it? Any help will be greatly appreciated.
LActivity
public class LActivity extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Location1";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public Location mCurrentLocation;
String mLastUpdateTime;
ViewPager viewPager;
ProgressDialog progressdialog;
protected void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Pending");
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progressdialog.cancel();
}
};
Handler pdcanceller = new Handler();
pdcanceller.postDelayed(progressRunnable,1500);
progressdialog.show();
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_rape_location);
viewPager = (ViewPager) findViewById(R.id.viewpagerL);
viewPager.setAdapter(new RapeLocationPageAdapter(getSupportFragmentManager(),
LActivity.this));
}
public void getLocation(View view) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 501);
} else {
mGoogleApiClient.connect();
}
progressdialog.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 501) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mGoogleApiClient.connect();
} else {
Toast.makeText(this, "Location permission denied. Please grant location permission to the app.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
progressdialog.show();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
{
final AlertDialog builder = new AlertDialog.Builder(this).create();
builder.setMessage("Location has not been granted");
builder.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
builder.dismiss();
}
});
builder.show();
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
progressdialog.show();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
final AlertDialog builder = new AlertDialog.Builder(this).create();
builder.setMessage("If there are no locations near you, please contact the local police for immediate attention");
builder.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
builder.dismiss();
}
});
builder.show();
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
RapeLocation rapeLocation = (RapeLocation) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpagerRape + ":" + viewPager.getCurrentItem());
rapeLocation.update(mCurrentLocation);
}
}
LActivityMain
public class LActivityMain extends Fragment {
RecyclerView recyclerView;
LocationsAdapter locationsAdapter;
ArrayList<LocationModel> locationModelArrayList = new ArrayList<LocationModel>();
ArrayList<LocationModel> filteredlocationModelArrayList = new ArrayList<LocationModel>();
protected DatabaseReference mDatabase;
LActivityMain locationActivityfin;
Button bnt1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_locationmain, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
locationActivityfin = (LActivityMain) getActivity();
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.rvLocations);
bnt1 = view.findViewById(R.id.locdone);
bnt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
locationsAdapter = new LocationsAdapter(getActivity(), new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
LatLng latLng = new LatLng(filteredlocationModelArrayList.get(position).getLatitude(),
filteredlocationModelArrayList.get(position).getLongitude());
String url = "http://maps.google.com/maps?saddr=" + locationActivityfin.mCurrentLocation.getLatitude() + "," + locationActivityfin.mCurrentLocation.getLongitude() + "&daddr=" + latLng.latitude + "," + latLng.longitude + "&mode=driving";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(url));
PackageManager packageManager = getActivity().getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
} else {
if (getView() != null)
Snackbar.make(getView(), "Make sure Google Maps is installed to use this feature", Snackbar.LENGTH_LONG).show();
}
}
}, filteredlocationModelArrayList);
getDataFromServer();
//textView.setText(getArguments().getDouble("latitude") + ", " + getArguments().getDouble("longitude"));
}
public void update(Location location) {
// Toast.makeText(getActivity(), "updated", Toast.LENGTH_SHORT).show();
filteredlocationModelArrayList.clear();
for (LocationModel locationModel : locationModelArrayList) {
Location location1 = new Location("Loc");
location1.setLatitude(locationModel.getLatitude());
location1.setLongitude(locationModel.getLongitude());
if (location1.distanceTo(location) <= 50000 && filteredlocationModelArrayList.size() < 30) {
double distance = (double) (location1.distanceTo(location) / 1000);
try {
distance = round(distance, 2);
} catch (Exception e) {
}
locationModel.setDistance(distance);
filteredlocationModelArrayList.add(locationModel);
}
locationsAdapter.update(filteredlocationModelArrayList);
}
}
public double round(double value, int places) {
if (places <= 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
void getDataFromServer() {
mDatabase.child("ali").child("location221").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataChild : dataSnapshot.getChildren()) {
LocationModel locationModel = dataChild.getValue(LocationModel.class);
locationModelArrayList.add(locationModel);
}
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(locationsAdapter);
if (locationActivityRape.mCurrentLocation != null) {
update(locationActivityRape.mCurrentLocation);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Assuming you have figured out how to tell that some resource is within some distance from the app, the next question is do you want this to update the app over its entire lifecycle or just at startup or resume.
For the former, as part of your app initialization you start up a timed task of some sort. You want this code to be off the UI thread, and it probably needs to use the network to do its job. The idea is that this task wakes up periodically and does whatever it needs to do to check for external resources.
As long as it finds some valid resource(s) it just goes back to sleep. If it finds no valid resources it then either invokes a callback method or raises an intent that your client code listens for to display a dialog, ring a bell, etc. Make sure you shut down this task when cleaning up your app, and make sure you can cancel the running state and/or it handles and uses timeouts.
If only once on startup just fire off an AsyncTask that gets some results, and then reports via its UI thread handler (or communicates back to the caller) so a dialog can be shown and perhaps the app closed (if these resources are critical to the app lifecycle).
Related Q&A: Timertask or Handler, AsyncTask Android example (But there are many others resources out there.)
I've got problem. I need only one information about location. I want to click on my button, get location and stop GPS. But in my case it gives me informations about location every 5 seconds. It'S possible to make it work, how i want it? Because i want to save data about start of road in sqlite database. So i need only one information about location. Like my first idea, or the most simple thing i can do, was making the time interval larger than five seconds, something like 5 000 000 seconds. But it's not the best solution i think. :)
this is my code
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent dbmanager = new Intent(MainActivity.this, AndroidDatabaseManager.class);
startActivity(dbmanager);
}
});
locLIST = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
gps1.append("\n " + location.getLatitude() + " " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.INTERNET
},10);
return;
}else{
configureButton();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 10:
if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED)
configureButton();
return;
}
}
private void configureButton() {
buttonGPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locman.requestLocationUpdates("gps", 0, 0, locLIST);
}
});
}
No bug, but the distance keeps changing when i click test button(not every 5s), so i dunno if my code really works well or not. It would be appreciated if you can tell whether there is some logical error or not.
here is my code.
The logic here is, when i have clicked start button, it will get the location, and then in every 5s, it will get a new location and calculate the distance and store it in an array. When i press test button, the total distance will be shown
public class MapsActivity extends BaseActivity /*implements LocationListener*/{
double totalDis=0;
double l;
int oxy =0;
TimeAnimator anim = new TimeAnimator();
private int isReset = 1;
private TextView textTimer;
private Button startButton;
private Button pauseButton;
private Button resetButton;
private long startTime = 0L;
private Handler myHandler = new Handler();
long timeInMillies = 0L;
long timeSwap = 0L;
long finalTime = 0L;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private GoogleMap mMap;
private Button testbtn;
double x;
double y;
double j;
double k;
float [] dis = new float[6];
TextView txt;
Location locationA;
Location locationB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
// titles
// from
// strings.xml
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
textTimer = (TextView) findViewById(R.id.textTimer);
testbtn = (Button) findViewById(R.id.testbtn);
txt = (TextView) findViewById(R.id.textTest);
testbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for(int i=0;i<dis.length;i++){
totalDis+=dis[i];
}
txt.setText("dis = "+totalDis);
}
});
startButton = (Button) findViewById(R.id.btnStart);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location locationA = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
x = locationA.getLatitude();
y = locationA.getLongitude();
anim.start();
anim.setTimeListener(new TimeAnimator.TimeListener() {
long time = 0;
#Override
public void onTimeUpdate(TimeAnimator timeAnimator, long t, long dt) {
time += dt;
if (time >= 5000) { // >= needed because this also might be not totally accurate...
time -= 5000; // keep the remainder (if there is) to correct the accuracy of next loop
// do stuff here (in every 5 seconds)
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location locationB = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
j = locationB.getLatitude();
k = locationB.getLongitude();
Location.distanceBetween(x,y,j,k,dis);
x=j;
y=k;
}
}
});
}
});
pauseButton = (Button) findViewById(R.id.btnPause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwap += timeInMillies;
myHandler.removeCallbacks(updateTimerMethod);
}
});
resetButton = (Button) findViewById(R.id.btnReset);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
textTimer.setText("0:00:00");
timeSwap=0;
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
}
private Runnable updateTimerMethod = new Runnable() {
public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
textTimer.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliseconds));
myHandler.postDelayed(this, 0);
}
};
}
put these codes into yours as directed .
declair these veriables
LocationManager manager;
Button start_calculating, show;
boolean startcount_now = false;
double total_dist = 0;
Location last_loc = null;
import
import android.location.LocationListener;
and implement
LocationListener
then implement these methods
#Override
public void onLocationChanged(Location location) {
if (startcount_now == true) {
if (last_loc == null) {
last_loc = location;
} else {
total_dist += location.distanceTo(last_loc);
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
if (manager != null) {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
}
}
#Override
protected void onPause() {
super.onPause();
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
if (manager != null) {
manager.removeUpdates(MainActivity.this);
}
}
in oncreate()
manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
the listeners for the button (you add these into your own button used for this purpose)
start_calculating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startcount_now = true;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "total distancetravelled is " + total_dist, Toast.LENGTH_LONG).show();
}
});
add permission in menifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
the show button will show you the total distance in toast . you can use as you want it. the location fetching will be stopped when your app is in background. for the location fetching mechanism please read this.
let me know if this is what you want.
Your code is very very wrong.
Refer to Receiving Location updates page. That page leaves some stuff for you to implement, so I'll give you working example. You'll need to adapt it for your needs yourself.
#Override
public void onConnected(#Nullable final Bundle bundle) {
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(final int i) {
}
#Override
public void onLocationChanged(final Location location) {
EventBus.getDefault().post(new LocationChangedEvent(location));
}
#Override
public void onConnectionFailed(#NonNull final ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
Logger.e(this, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Utils.showPermissionRationaleDialog(MainActivity.this, R.string.permission_rationale_location,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
});
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
"request_location_updates");
}
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
In my mainActivity I have a listview where the user can select one. As a sample, there are 3 list in the mainActivity which is startTripActivity, ClockinActivity, CustomerSvcActivity.
For starttripactivity, the user would click that and it would show the button and once clicked it would show toast message info of their location and send to the server. For clockinActivity, user can click to display the current time/date and click the button to send that data to the server.
For customersvcActivity, user would click the button and it will open the barcode scanner and return the result and send that to the server. What I want to do is each of those activity that was sent to the server I also want to send the gps location with the data. Example, starttrip would send the gps info to the server, clockin would send the clockin time/date plus their gps location info where they clocked in, and barcode result data plus their gps location info where they scanned the code sent to the server.
I would like to see some samples and suggestions. All the searches I've found are mostly how to get the gps data every xx minutes which isnt exactly what im looking for and few others doesn't really help me much. The very bottom of this post are the codes of my sample communicating with the webserver.
Thanks
MainActivity.java
public class Customer extends ListActivity
{
CustomerListItem[] items = {
new CustomerListItem("Start Trip", StartTripActivity.class),
new CustomerListItem("Clock in", ClockinActivity.class),
new CustomerListItem("Customer Svc", CustomerSvcActivity.class),
private String username;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.customer);
setListAdapter(new ArrayAdapter<CustomerListItem>(
this, android.R.layout.simple_list_item_1, items));
selection = (TextView) findViewById(R.id.selection);
resultsTxt = (TextView) findViewById(R.id.cancel);
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent(this, items[position].getActivity());
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
// Perform different actions based on from which activity is
// the application returning:
switch (requestCode)
{
case 0:
// TODO: handle the return of the StartTripActivity
break;
.............
}
StartTripActivity
public class StartTripActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
private void Pop(String string) {
// TODO Auto-generated method stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(StartTripActivity.this, message,
Toast.LENGTH_LONG).show();
}
Intent i = new Intent(getApplicationContext(), Customer.class);
startActivity(i);
}
class MyLocationListener implements LocationListener {
#SuppressWarnings("null")
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(StartTripActivity.this, message, Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(StartTripActivity.this, "Provider status changed",
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(StartTripActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(StartTripActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
ClockinActivity.java
public class ClockinActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clockin);
TextView textView= (TextView)findViewById(R.id.Date);
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
textView.setText(currentDateTimeString);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Pop("Back Button");
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void Pop(String string) {
// TODO Auto-generated method stub
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":"+ minutes + ":"+ seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {
}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
Button btn = (Button) findViewById(R.id.btn_OK);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Customer.class);
startActivity(i);
//finish();
}
CustomerSvcActivity.java
public class CustomerSvcActivity extends Activity {
private Button btnscan;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
this.startActivity(new Intent(CustomerSvcActivity.this,Customer.class));
}
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customersvc);
btnscan = (Button) findViewById(R.id.scanbtn);
btnscan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
IntentIntegrator.initiateScan(CustomerSvcActivity.this);
}
});
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
switch(requestCode) {
case IntentIntegrator.REQUEST_CODE: {
if (resultCode != RESULT_CANCELED) {
IntentResult scanResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
String upc = scanResult.getContents();
// need to return the result without display and send to server???
}
}
break;
Sample class of sending data
public class Sample extends Activity {
/** Called when the activity is first created. */
TextView result;
EditText text;
Button send;
private ArrayList<NameValuePair> postParameters;
AlertDialog.Builder alert;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alert = new AlertDialog.Builder(this);
alert.setCancelable(true);
result=(TextView)findViewById(R.id.result);
text=(EditText)findViewById(R.id.text);
send=(Button)findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//postParameters.add(new BasicNameValuePair("text",
//text.getText().toString()));
postData(text.getText().toString());
//saveData();
showData();
}
public void showData()
{
try {
String response = CustomHttpClient
.executeHttpGet("http://www.merrill.com/android.php");
result.setText(response);
} catch (Exception e) {
}
}
Android's Location API is periodic only. If you want a one-off location fix triggered by any of the user's actions, you can use LocationManager.getLastKnownLocation(), but you'll want to check the returned fix's time stamp. To get a new fix what you really need to do is:
-request location data using a small period time
-wait until the first location fix comes in
-cancel your location request
This will require asynchronous communication, which you can do however you're most comfortable with. You can use callback functions or pass in a runnable or a message passing system if you have access to one that's easy to include. The GPS might take a couple minutes to return, and it might not be able to get a valid fix so you'll have to account for that.
Hope this helps.