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

Posted

技术标签:

【中文标题】未获取位置时关闭应用程序的对话框【英文标题】:Dialog to close application in between when location is not fetched 【发布时间】:2016-01-06 01:03:54 【问题描述】:

我正在开发地图应用程序。

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

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

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

以下是我必须使用它的活动。

Tripdetails.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();


 

任何帮助表示赞赏..!!

【问题讨论】:

您希望此检查一直在后台执行吗? 是的。每次如果“未检索到位置”吐司被执行。 然后您可以为此编写一个Service 类。在该Service 中,创建一个扩展LocationListener 的类。检查位置,如果它返回null,则显示Toast . 请检查我的代码。我已经实现了,如果无法检索到位置,Toast 将显示,但在执行该 toast 后,我​​需要显示一个对话框“你是否要关闭应用程序”。 我认为您在执行位置检查时遇到问题。请在下面查看我的答案。它应该可以工作 【参考方案1】:

试试这个:

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

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();

【讨论】:

嘿,谢谢。这是有效的。在代码中,添加了以下行而不是第一行。 "final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); builder.setTitle("Close Application")"【参考方案2】:

尝试关闭应用程序:

quitBtn.setOnClickListener(new View.OnClickListener()          
        @Override
        public void onClick(View paramView) 
      
            finish();          
            moveTaskToBack(true);
        
    );

【讨论】:

这必须在其他部分完成,而不是在按钮点击时完成。 在任何你喜欢的地方使用它。

以上是关于未获取位置时关闭应用程序的对话框的主要内容,如果未能解决你的问题,请参考以下文章

Android运行时权限对话框未显示

Facebook 连接对话框未关闭

屏幕关闭时,前台服务未在 Android 7.0+ 中接收位置更新

Gps 位置图标未关闭

如何在应用程序关闭之前显示未保存的更改对话框? [关闭]

当我在 GPS 关闭的情况下启动应用程序,后来 GPS 被激活时,未检测到位置