java - Call PHP function using Android
I need to call a function in a php file which uses latitude and longitude to calculate the distance moved. Very unsure how to do it, so would love some suggestions.
PS: I know it'd be easier to calculate it without using PHP but unfortunately I am required to do it this way...
Here's my code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String URL = "http://192.168.0.105/location.php";
private final static int REQUEST_CODE_LOCATION_PERMISSION = 1;
public Button startButton;
public TextView distance;
public double lat1, long1, lat2, long2, latitude, longitude;
public boolean checkLoc = false;
public boolean running = false;
public String locString = "loc1";
final Handler handler = new Handler();
int interval = 10000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = findViewById(R.id.startButton);
distance = findViewById(R.id.distView);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startButton.setEnabled(false);
running = true;
}
});
if (running = true){
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION_PERMISSION);
} else {
getCurrentLocation();
}
System.out.println(locString);
if (locString.equals("loc1")){
lat1 = latitude;
long1 = longitude;
locString = "loc2";
} else if (locString.equals("loc2")){
lat2 = latitude;
long2 = longitude;
locString = "loc1";
}
if (lat1 != 0 && lat2 != 0){
}
System.out.println("Lat1: " + lat1 + "\nLat2: " + lat2);
handler.postDelayed(this, interval);
}
}, interval);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0) {
getCurrentLocation();
} else {
Toast.makeText(this, "Permission denied!", Toast.LENGTH_SHORT).show();
}
}
private void getCurrentLocation() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.getFusedLocationProviderClient(MainActivity.this)
.requestLocationUpdates(locationRequest, new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LocationServices.getFusedLocationProviderClient(MainActivity.this)
.removeLocationUpdates(this);
if(locationResult != null && locationResult.getLocations().size() > 0){
int latestLocationIndex = locationResult.getLocations().size() - 1;
latitude = locationResult.getLocations().get(latestLocationIndex).getLatitude();
longitude = locationResult.getLocations().get(latestLocationIndex).getLongitude();
}
}
}, Looper.getMainLooper());
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dist_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.meter:
return true;
case R.id.km:
return true;
case R.id.miles:
return true;
}
return true;
}
}
location.php:
<?php
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
if (($lat1 == $lat2) && ($lon1 == $lon2)) {
return 0;
}
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) *
sin(deg2rad($lat2)) + cos(deg2rad($lat1)) *
cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
}else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
/*Write the scripts to extract the latitude and longitude from your URL*/
?>
Answer
Solution:
I recommend these libraries to call php function.
First of all, request a permission to access network, add following to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Then the easiest way is to use Apache http client bundled with Android:
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
Source