Android 如果GPS未打开,活动崩溃;如果GPS不可用,是否可以使用粗略的位置?

Android 如果GPS未打开,活动崩溃;如果GPS不可用,是否可以使用粗略的位置?,android,Android,当我在设备上关闭GPS的情况下加载此活动时,它会使应用程序崩溃 我该如何着手解决这个问题 如果可能的话,如果GPS被关闭,而不是使用粗略的位置,这也将是令人惊讶的,不知道这将是多么容易 非常感谢您的帮助,代码如下: public class SunriseSunset extends Activity implements OnClickListener { public Button getLocation; public Button setLocationJapan;

当我在设备上关闭GPS的情况下加载此活动时,它会使应用程序崩溃

我该如何着手解决这个问题

如果可能的话,如果GPS被关闭,而不是使用粗略的位置,这也将是令人惊讶的,不知道这将是多么容易

非常感谢您的帮助,代码如下:

public class SunriseSunset extends Activity implements OnClickListener {

    public Button getLocation;
    public Button setLocationJapan;
    public TextView LongCoord;
    public TextView LatCoord;
    public double longitude;
    public double latitude;
    public LocationManager lm;
    public Spinner Locationspinner;
    public DateDialogFragment frag;
    public Button date;
    public Calendar now;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sunrisesunset);
        // Show the Up button in the action bar.
                setupActionBar();

        //Setting onClickListener for Calculate Sunrise/Sunset Button
        findViewById(R.id.CalculateSunriseSunset).setOnClickListener(this);

        //Sets up LocationManager to enable GPS data to be accessed.
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                new MyLocationListener());

        //Declares Latitude and Longitude TextViews
        LatCoord = (TextView) findViewById(R.id.LatCoord);
        LongCoord = (TextView) findViewById(R.id.LongCoord);

        //Declares for Location Spinner/Dropdown
        addListenerOnSpinnerItemSelection();

        //Date shit
        now = Calendar.getInstance();
        date = (Button)findViewById(R.id.date_button);
        date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance()));
        date.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog();
            }
        });

    }
    /**
     * Set up the {@link android.app.ActionBar}.
     */
    private void setupActionBar() {

        getActionBar().setDisplayHomeAsUpEnabled(true);

    }

    // More date shit
    @SuppressLint("CommitTransaction")
    public void showDialog() {  
        FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment   
        frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){      

        public void updateChangedDate(int year, int month, int day){                     
        now.set(year, month, day);
        date.setText(DateFormat.format("dd MMMM yyyy", now));             
        }  
          }, now);
        frag.show(ft, "DateDialogFragment");     }



    public interface DateDialogFragmentListener{
        //this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
        public void updateChangedDate(int year, int month, int day);
    }

    public void addListenerOnSpinnerItemSelection() {
        Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
        Locationspinner
                .setOnItemSelectedListener(new LocationOnItemSelectedListener(
                        this));
    }

    //Sets locations for all the cities in the spinner
    public void setLocationAuckland() {LatCoord.setText("-36.85248273");LongCoord.setText("174.76391734");}
    public void setLocationBuenoAires() {LatCoord.setText("-34.606358325");LongCoord.setText("-58.38727463");}
    public void setLocationCalgary() 

    protected void showCurrentLocation() {
        // TODO Auto-generated method stub
        // This is called to find current location based on GPS data and sends
        // these values to the LongCoord and LatCoord TextViews
        Location location = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }

    @Override
    public void onClick(View arg0) {
        Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
        b.setClickable(false);
        new LongRunningGetIO().execute();
    }

    public class LongRunningGetIO extends AsyncTask<Void, Void, String> {
        //Reads in the web service
        protected String getASCIIContentFromEntity(HttpEntity entity)
                throws IllegalStateException, IOException {
            InputStream in = entity.getContent();
            StringBuffer out = new StringBuffer();
            int n = 1;
            while (n > 0) {
                byte[] b = new byte[4096];
                n = in.read(b);
                if (n > 0)
                    out.append(new String(b, 0, n));
            }
            return out.toString();
        }

        private final ProgressDialog dialog = new ProgressDialog(SunriseSunset.this);

        protected void onPreExecute() {
           this.dialog.setMessage("Calculating...");
           this.dialog.show();
        }

        @SuppressLint("SimpleDateFormat")
        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();

            // Finds todays date and adds that into the URL in simple date format DD/MM
            SimpleDateFormat df = new SimpleDateFormat("dd/MM");
            String formattedDate = df.format(now.getTime());

            String finalURL = "http://www.earthtools.org/sun/"
                    + LatCoord.getText().toString().trim() + "/"
                    + LongCoord.getText().toString().trim() + "/"
                    + formattedDate + "/99/0";
            HttpGet httpGet = new HttpGet(finalURL);
            String text = null;

            try {
                HttpResponse response = httpClient.execute(httpGet,
                        localContext);
                HttpEntity entity = response.getEntity();
                text = getASCIIContentFromEntity(entity);
            } catch (Exception e) {
                return e.getLocalizedMessage();
            }
            return text;
        }

        protected void onPostExecute(String results) {
            //Closes dialog box onPostExecute
            if (this.dialog.isShowing()) {
                  this.dialog.dismiss();
               }
            //Finds TextViews for Sunrise and Sunset values and posts results
            if (results != null) {
                try {

                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                            .newInstance();
                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                    InputSource s = new InputSource(new StringReader(results));
                    Document doc = dBuilder.parse(s);
                    doc.getDocumentElement().normalize();
                    TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
                    TextView tvSunset = (TextView) findViewById(R.id.Sunset);
                    tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
                    tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
            b.setClickable(true);
        }
    }



    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home, menu);
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        //  preparation code here
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        if (item.getItemId() == R.id.LessonsTutorials) {
            startActivity(new Intent(this, Lessons.class));
        }
        if (item.getItemId() == R.id.PhotoTools) {
            startActivity(new Intent(this, Tools.class));
        }
        if (item.getItemId() == R.id.Glossary) {
            startActivity(new Intent(this, Glossary.class));
        }
        if (item.getItemId() == R.id.Help) {
            startActivity(new Intent(this, Help.class));
        }
        return super.onOptionsItemSelected(item);
    }

}
编辑:

是因为我打电话给这里的GPS_提供商:

protected void showCurrentLocation() {
        // TODO Auto-generated method stub
        // This is called to find current location based on GPS data and sends
        // these values to the LongCoord and LatCoord TextViews
        Location location = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }

任何提供者都可能不可用。因此,在请求更新之前,请务必检查

if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
            new MyLocationListener());
} else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1,
            new MyLocationListener());
}
此外,LocationManager可能不可用(没有位置功能的设备或固件)。所以也要检查null。 我几乎不理解你的目标,但从我看来,我会这样做

private boolean pending;

private LocationListener listener;
private LocationManager lm;

@Override
protected void onCreate(Bundle state) {
    //your stuff
    listener = new MyLocationListener();
}

@Override
protected void onPostCreate(Bundle state) {
    super.onPostCreate(state);
    if (lm != null) {
        requestLocation();
    }
}


private void requestLocation() {

    if (!pending) {

        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                    listener);
            pending = true;
        } else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1,
                    listener);
            pending = true;
        }

    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (pending) {
        lm.removeUpdates();
    }
}
编辑关于showCurrentLocation的信息:

protected void showCurrentLocation() {
    // these values to the LongCoord and LatCoord TextViews
    Location location = lm
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }
}

任何提供者都可能不可用。因此,在请求更新之前,请务必检查

if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
            new MyLocationListener());
} else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1,
            new MyLocationListener());
}
此外,LocationManager可能不可用(没有位置功能的设备或固件)。所以也要检查null。 我几乎不理解你的目标,但从我看来,我会这样做

private boolean pending;

private LocationListener listener;
private LocationManager lm;

@Override
protected void onCreate(Bundle state) {
    //your stuff
    listener = new MyLocationListener();
}

@Override
protected void onPostCreate(Bundle state) {
    super.onPostCreate(state);
    if (lm != null) {
        requestLocation();
    }
}


private void requestLocation() {

    if (!pending) {

        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                    listener);
            pending = true;
        } else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1,
                    listener);
            pending = true;
        }

    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (pending) {
        lm.removeUpdates();
    }
}
编辑关于showCurrentLocation的信息:

protected void showCurrentLocation() {
    // these values to the LongCoord and LatCoord TextViews
    Location location = lm
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }
}

stacktrace是否来自logcat?是否已将权限添加到添加的manifest@SankarV logcat输出above@John-是的,两个权限都在清单文件中:)我想我有你问题的答案,但是我无法向你发布答案。当我尝试向你发布答案时,我收到了此消息-“您的帖子似乎包含未正确格式化为代码的代码。“…那么,让我试着用某种方式从logcat向您提供答案StackTrace?您是否将权限添加到了manifest@SankarV logcat输出中?”above@John-是的,两个权限都在清单文件中:)我想我有你问题的答案,但我无法将答案发布给你当我试着把答案贴在你的帖子上时,得到了这个消息——“你的帖子似乎包含的代码格式不正确。“…让我试着用某种方式为你提供答案最好的方式是用某种方法来回答。这取决于你的目标是什么。如果要在活动创建后请求,可以在onCreate()中调用它。如果要在每次活动获得焦点时请求,请在onResume()中调用它。您还必须检查位置更新是否已挂起,并且在不需要更新时不要忘记停止更新,请在onDestroy()或onPause()中使用lm.removeUpdates(侦听器)(如果在onResume()中)或者点击按钮事件。这取决于您。实现了该示例,但它仍然崩溃,并给出了相同的信息:为什么您不学习找出自己的错误?它仍然存在吗(SunriseSunset.java:148)导致NullPointerException的原因是什么?此时您的lm似乎为null。最好的方法是将其放在某个方法中。这取决于您的目标。若要在活动创建后请求,可以在onCreate()中调用它。若要在每次活动获得焦点时请求,请在onResume()中调用它。您还必须检查位置更新是否已挂起,并且在不需要更新时不要忘记停止更新,请在onDestroy()或onPause()中使用lm.removeUpdates(侦听器)(如果在onResume()中)或者点击按钮事件。这取决于您。实现了该示例,但它仍然崩溃,并给出了相同的消息:为什么您不学习找出自己的错误?是否仍然(SunriseSunset.java:148)导致NullPointerException?看起来您当时的lm为null。