java - 未获取位置时关闭应用程序的对话框

标签 java android google-maps

我正在开发 map 应用程序。

在编辑文本字段应用程序中自动获取用户位置。如果未获取位置,则必须打开一个对话框,显示“无法获取位置,是否要关闭应用程序?”。

onBackPressed() 可用于在按下后退按钮时关闭应用程序。

但我希望这发生在应用程序运行之间。

下面是我必须使用它的 Activity 。

行程详情.java

public class TripDetails extends Activity implements LocationListener {


EditText pres_location, destination_et;
protected LocationManager locationManager;

protected Context context;
ImageView destination_icon;
Button done, cancel;
Double deslat, deslong;
String veh;
String provider;
Location location;
EditText vechile;
SharedPreferences pref;
// protected String latitude,longitude;
//  protected boolean gps_enabled,network_enabled;

String logDate, logLatitude = "no data avilable",
        logLongtitude = "no data avilable",
        logAddress = "no data avilable";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip_details);

    vechile = (EditText) findViewById(R.id.vechile_number);
    veh = vechile.getText().toString();

    pres_location = (EditText) findViewById(R.id.present_location);
    destination_icon = (ImageView) findViewById(R.id.destination_icon);
    destination_et = (EditText) findViewById(R.id.et_destination);
    done = (Button) findViewById(R.id.btn_done);
    cancel = (Button) findViewById(R.id.btn_cancel);


    pref = getSharedPreferences("gps", Context.MODE_PRIVATE);


//gps checking
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
    } else {
        showGPSDisabledAlertToUser();
    }


    done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplication(),"Alert has been sent to your emergency contact.",Toast.LENGTH_SHORT).show();
            new Thread(new Runnable() {
                public void run() {
                    if ((!pres_location.getText().toString().equals("")) && (!destination_et.getText().toString().equals("")) && (!vechile.getText().toString().equals(""))) {
                        String a = pref.getString("mobile", "");
                        String a2 = pref.getString("mobile2", "");
                        String name = pref.getString("Name", "");


                        /*SmsManager smsManager = SmsManager.getDefault();
                        smsManager.sendTextMessage(a, null, "Your Friend " + name + " " + "travelling from " + pres_location.getText().toString()
                                + " " + "to:" + destination_et.getText().toString()
                                + ", in V.No " + vechile.getText().toString()
                                , null, null);
                        smsManager.sendTextMessage(a2, null, "Your Friend " + name + " " + "travelling from " + pres_location.getText().toString()
                                + " " + "to:" + destination_et.getText().toString()
                                + ", in V.No " + vechile.getText().toString()
                                , null, null);

*/

                                Intent in = new Intent(TripDetails.this,
                                MapsActivityConnect.class);
                        in.putExtra("deslatitude", deslat);
                        in.putExtra("deslongitude", deslong);
                        in.putExtra("srclatitude", location.getLatitude());
                        in.putExtra("srclongitude", location.getLongitude());
                        startActivity(in);


                    } else {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplication(), "Please check your network", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }


                }
            }).start();
        }
    });


    destination_icon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {
                public void run() {

                    Intent in = new Intent(TripDetails.this,
                            MapsActivity.class);

                    startActivity(in);
                }
            }).start();

        }
    });


    // Getting LocationManager objectlatitude
    locationManager = (LocationManager)

            getSystemService(Context.LOCATION_SERVICE);

    // Creating an empty criteria object
    Criteria criteria = new Criteria();

    // Getting the name of the provider that meets the criteria
    provider = locationManager.getBestProvider(criteria, true);

    if (provider != null && !provider.equals(""))

    {

        // Get the location from the given provider
        location = locationManager.getLastKnownLocation(provider);


        locationManager.requestLocationUpdates(provider, 2000, 0, this);

        if (location != null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();

    } else

    {
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        onBackPressed();

    }


    Spinner dropdown = (Spinner) findViewById(R.id.spinner1);
    String[] items = new String[]{"Car", "Bus", "Bike", "Train", "Flight"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
    dropdown.setAdapter(adapter);

    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(TripDetails.this,
                    Sign_in.class);

            startActivity(in);
        }
    });

}


@Override
public void onLocationChanged(Location location) {
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        deslat = extras.getDouble("latitude");
        deslong = extras.getDouble("longitude");
        destination_et.setText(getCompleteAddressString(deslat, deslong));


    }

    pres_location.setText(getCompleteAddressString(location.getLatitude(), location.getLongitude()));


}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.d("Latitude", "status");
}

@Override
public void onProviderEnabled(String provider) {
    Log.d("Latitude", "Enable");
}

@Override
public void onProviderDisabled(String provider) {
    Log.d("Latitude", "disable");
}

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {


    String loc = null;
    Address returnedAddress = null;

    // geocode object is created
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        // address is derived
        List<Address> addresses = geocoder.getFromLocation(LATITUDE,
                LONGITUDE, 1);
        if (addresses != null) {

            returnedAddress = addresses.get(0);

            // address details are retrived line by line
            if (returnedAddress != null) {
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < returnedAddress
                        .getMaxAddressLineIndex(); i++) {
                    sb.append(returnedAddress.getAddressLine(i));
                }

                loc = sb.toString();

                // Toast.makeText(getBaseContext(), "address is   "+loc, Toast.LENGTH_SHORT).show();

                logAddress = loc;

                logLatitude = Double.toString(LATITUDE);
                logLongtitude = Double.toString(LONGITUDE);


            } else {

            }
        } else {

        }
    } catch (Exception e) {
        e.printStackTrace();

    }

    return loc;
}

private void showGPSDisabledAlertToUser() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Goto Settings Page To Enable GPS",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Intent callGPSSettingIntent = new Intent(
                                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(callGPSSettingIntent);
                        }
                    });
    alertDialogBuilder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

 }

感谢任何帮助..!!

最佳答案

试试这个:

将此代码放入位置为空的条件中。

new AlertDialog.Builder(context)
    .setTitle("Close Application")
    .setMessage("Do you want to close the Application?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            finish();
        }
     })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // do nothing
        }
     })
    .setIcon(android.R.drawable.ic_dialog_alert)
     .show();

关于java - 未获取位置时关闭应用程序的对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015260/

相关文章:

java - Keycloak - 自定义 SPI 未出现在列表中

Java如何从文件和cli中读取参数?

android - 启动和停止notificationlistener服务

java - 折线未从 GoogleMap 中删除

java - 标记多个 fragment Google Maps API 2

java - Spring 数据 Jpa : Multiple ContainingIgnoreCase

java - 使用for循环java逆向生成一个数字

android - 在 ASUS MeMo FHD 10 上通过 USB 调试 Adob​​e AIR 应用程序

android - 如何在不同的移动平台上以同样的方式展示内容?

android - 如何获取谷歌地图API key