i want the maps like search view where we search places To and From (when we start typing the name of the street, the details of the street should be displayed below with the help of autocomplete Text view)i am using the Places API but its not working as i want
Java.Class
public class GpsLocation extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
AutoCompleteTextView autocomplete_places;
Button auto, next;
private static final String TAG = "GpsLocation";
private static final long INTERVAL = 10000 * 10;
private static final long FASTEST_INTERVAL = 10000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
SharedPreferences preferences;
SharedPreferences.Editor editorpref;
GPSTracker gps;
private PlaceAutoCompleteAdapter mAdapter;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.location);
autocomplete_places = (AutoCompleteTextView) findViewById(R.id.autocomplete_places);
auto = (Button) findViewById(R.id.auto);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
autocomplete_places.setAdapter(new PlaceArrayAdapter(getApplicationContext(), R.layout.autocomplete_list_item));
autocomplete_places.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String description = (String) adapterView.getItemAtPosition(i);
Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
}
});
auto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gps = new GPSTracker(getApplicationContext());
if (gps.canGetLocation()){
updateUI();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GpsLocation.this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
if (!isGooglePlayServicesAvailable()) {
finish();
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
double lat = Double.parseDouble(String.valueOf(mCurrentLocation.getLatitude()));
double lng = Double.parseDouble(String.valueOf(mCurrentLocation.getLongitude()));
Log.d("Location", String.valueOf(lat + lng));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
String city = addresses.get(0).getAddressLine(2);
Toast.makeText(GpsLocation.this, city, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
}
PlaceArray Adapter.class
public class PlaceArrayAdapter extends ArrayAdapter<String> implements Filterable {
ArrayList<String> resultList;
Context mContext;
int mResource;
PlaceApi mPlaceAPI = new PlaceApi();
public PlaceArrayAdapter(Context context, int resource) {
super(context, resource);
mContext = context;
mResource = resource;
}
#Override
public int getCount() {
// Last item will be the footer
return resultList.size();
}
#Override
public String getItem(int position) {
return resultList.get(position);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = mPlaceAPI.autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.autocomplete_list_item, null);
if (position != (resultList.size() - 1)) {
TextView autocompleteTextView = (TextView) view.findViewById(R.id.autocompleteText);
autocompleteTextView.setText(resultList.get(position));
}
return view;
}
}
Related
I am developing android app for sharing data between two devices using Wifi Direct all is working great i am able to show peers list in my app and can transfer data between them.
my only problem is in my peer list i just want to show the devices which are using my app and will show on senders phone when they are on receiving mode.
i found related question of my problem but not useful for me.
android wifi p2p : peers discovery filtering
Here is my transfer fragment in which i am getting peers list
public class TransferFragment extends Fragment implements LocationListener, peerListClickListener {
private static final String TAG = TransferFragment.class.getName();
private WifiP2pManager mWifiP2pManager;
private WifiP2pManager.Channel mChannel;
private List<WifiP2pDevice> mPeerList = new ArrayList<>();
private IntentFilter mIntentFilter;
private BroadcastReceiver mReceiver;
PeerListAdapter peerListAdapter;
LocationManager locationManager;
RecyclerView peersRecyclerView;
String provider;
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
try {
startDiscoverPeers();
mHandler.postDelayed(this, 8000);
} catch (Exception e) {
e.printStackTrace();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initWifiP2p();
getActivity().registerReceiver(mReceiver, mIntentFilter);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
assert locationManager != null;
provider = locationManager.getBestProvider(new Criteria(), false);
}
#Override
public void onResume() {
super.onResume();
mHandler.post(mRunnable);
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(mReceiver);
}
private void initWifiP2p() {
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mWifiP2pManager = (WifiP2pManager) getActivity().getSystemService(Context.WIFI_P2P_SERVICE);
assert mWifiP2pManager != null;
mChannel = mWifiP2pManager.initialize(getActivity(), getActivity().getMainLooper(), null);
mReceiver = new WiFiDirectReceiver(mWifiP2pManager, mChannel, (MainActivity) getActivity());
deletePersistentGroups();
}
private void deletePersistentGroups() {
try {
Method[] methods = WifiP2pManager.class.getMethods();
for (Method method : methods) {
if (method.getName().equals("deletePersistentGroup")) {
// Delete any persistent group
for (int netid = 0; netid < 32; netid++) {
method.invoke(mWifiP2pManager, mChannel, netid, null);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_transfer, container, false);
RippleBackground rippleBackground = view.findViewById(R.id.content);
rippleBackground.startRippleAnimation();
peersRecyclerView = view.findViewById(R.id.peer_recyclerview);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void startDiscoverPeers() {
mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.e(TAG, "discover success");
}
#Override
public void onFailure(int reason) {
Log.e(TAG, "discover failure");
}
});
}
public void stopDiscover() {
mHandler.removeCallbacks(mRunnable);
}
private void connectP2p(final WifiP2pDevice device) {
final WifiP2pConfig config = new WifiP2pConfig();
config.groupOwnerIntent = 0;
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.DISPLAY;
mWifiP2pManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getActivity(), "Connected To " + device.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int errorCode) {
}
});
}
public void updateList(WifiP2pDeviceList peers) {
mPeerList.clear();
mPeerList.addAll(peers.getDeviceList());//here i am getting devices list//
showPeersList();
}
#Override
public void onLocationChanged(Location location) {
}
#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 onPeerClicked(int position, WifiP2pDevice device) {
connectP2p(device);
peerListAdapter.notifyDataSetChanged();
}
public static String getDeviceStatus(int statusCode) {
switch (statusCode) {
case WifiP2pDevice.CONNECTED:
return "Connected";
case WifiP2pDevice.INVITED:
return "Invited";
case WifiP2pDevice.FAILED:
return "Failed";
case WifiP2pDevice.AVAILABLE:
return "Available";
case WifiP2pDevice.UNAVAILABLE:
return "Unavailable";
default:
return "Unknown";
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, TransferFragment.this);
}
}
}
}
}
private void showPeersList() {
peersRecyclerView.hasFixedSize();
peerListAdapter = new PeerListAdapter(mPeerList, getActivity(), this);
peersRecyclerView.setAdapter(peerListAdapter);
peersRecyclerView.setNestedScrollingEnabled(false);
peersRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
}}
I want to know is there any way to filter them or i need to make some kind of service in my app.
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 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.
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();
}
}
I am creating app that calculate distance. While running I tried setting priority=PRIORITY_BALANCED_POWER_ACCURACY with interval = 10 sec.
I tested it , it always return total distance = 0. Problem might be with priority and interval or my code.
What is most convenient priority and interval should be used ?
code
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {
private GoogleApiClient client;
private LocationRequest mLocationRequest ;
float distanceInMeters = 0;
TextView textView ;
Location A ;
Location B ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
A = new Location ("") ;
B = new Location ("") ;
}
public void activity (View v){
statusCheck();
startClient() ;
}
public void clear (View v){
if(client!=null) {
client.disconnect();
textView.setText(distanceInMeters + " m");
}
distanceInMeters = 0 ;
}
public void startClient (){
if(client==null) {
client = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
client.connect();
}
#Override
protected void onStop() {
super.onStop();
if(client!=null) {
client.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY );
mLocationRequest.setInterval(10000);
LocationServices.FusedLocationApi.requestLocationUpdates(client, mLocationRequest, this);
}
public float calculateDistance () {
if(A==null || A.getLatitude()==0){A=B;}
distanceInMeters = A.distanceTo(B);
Log.e("A","lat = "+A.getLatitude()+" lon = "+A.getLongitude() );
Log.e("B", "lat = " + B.getLatitude() + " lon = " + B.getLongitude());
Log.e("distance", "distance = " + distanceInMeters) ;
A =B ;
return distanceInMeters ;
}
#Override
public void onLocationChanged(Location location) {
B.setLatitude(location.getLatitude());
B.setLongitude(location.getLongitude());
calculateDistance();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void statusCheck() {
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
In onCreate, in the Location constructors, pass "gps" as an argument. See documentation for more info