public class MainActivity extends AppCompatActivity {
private static final int REQUEST_LOCATION=1;
public static Context gb;
static LocationManager locationManager;
public static String latitude,longitude;
public MainActivity(Context context){
this.gb = context;
}
Button getlocationBtn;
static TextView showLocationTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Add permission
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
showLocationTxt=findViewById(R.id.show_location);
getlocationBtn=findViewById(R.id.getLocation);
getlocationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//place the following line on all operations e.g click
locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Check gps is enable or not
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
//Write Function To enable gps
OnGPS();
}
else
{
//GPS is already On then
getLocation();
}
}
});
}
public static void getLocation() {
//Check Permissions again
if (ActivityCompat.checkSelfPermission(gb,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(gb, Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions((Activity)gb,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else
{
Location LocationGps= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location LocationNetwork=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location LocationPassive=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (LocationGps !=null)
{
double lat=LocationGps.getLatitude();
double longi=LocationGps.getLongitude();
latitude=String.valueOf(lat);
longitude=String.valueOf(longi);
showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
}
else if (LocationNetwork !=null)
{
double lat=LocationNetwork.getLatitude();
double longi=LocationNetwork.getLongitude();
latitude=String.valueOf(lat);
longitude=String.valueOf(longi);
showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
}
else if (LocationPassive !=null)
{
double lat=LocationPassive.getLatitude();
double longi=LocationPassive.getLongitude();
latitude=String.valueOf(lat);
longitude=String.valueOf(longi);
showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
}
else
{
Toast.makeText(gb, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
}
}
private void OnGPS() {
final AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog=builder.create();
alertDialog.show();
}
}
==================== Calling Activity ====================== ========
package com.example.currentlocation;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class calling extends AppCompatActivity {
Button btnLoc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
btnLoc = (Button) findViewById(R.id.getLocation);
btnLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.getLocation();
}
});
}
}
==================================== Вопрос = ===============================
Привет! Я пытаюсь написать код в java. Я хочу объявить все методы в одном классе с модификатором stati c. Чтобы при необходимости я мог вызывать этот метод и выполнять функцию, связанную с этим. в данном примере я пытаюсь вспомнить текущее местоположение, которое отлично работает при нажатии кнопки. но когда я пытаюсь вызвать это состояние c getLocation из другого действия, приложение вылетает.