简体   繁体   English

在 oncreate 方法中请求位置更新

[英]Requesting Location updates in oncreate method

I am trying to implement a location alarm kind of application.我正在尝试实现一种位置警报应用程序。 But whenever my application opens.但是每当我的应用程序打开时。 my current location shows as null.我当前的位置显示为空。

Below is my code.下面是我的代码。

package com.hrupin;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, LocationListener {


    private TextView setLat, setLong, destLat, destLong, currLat, currLong, tjd, fromhome, toward;
    private Button setmyLoc, setDest;

    private EditText editLat, editLong;

    private LocationManager orgManager;
    //private LocationListener orgListener;
    // private LocationListener destListener = new destListener();

    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    private String bestProvider;


    double orginLongitude, orginLatitude, destLongtitude, destLatitude, currLatitude, currLongtitude;
    float firstLat, firstLang, secLat, secLang;
    Location destinationLocation = new Location("gps");
    Location originLocation = new Location("gps");
    Location currLocation = new Location("gps");

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setLat = (TextView) findViewById(R.id.setLat);
        setLong = (TextView) findViewById(R.id.setLong);
        destLat = (TextView) findViewById(R.id.destLat);
        destLong = (TextView) findViewById(R.id.destLong);
        currLat = (TextView) findViewById(R.id.currLat);
        currLong = (TextView)findViewById(R.id.currLong);
        tjd = (TextView)findViewById(R.id.setmeter);
        fromhome = (TextView)findViewById(R.id.destmeter);
        toward = (TextView)findViewById(R.id.currmeter);

        setDest = (Button)findViewById(R.id.SetLocation);

        editLat = (EditText)findViewById(R.id.editLat);
        editLong = (EditText)findViewById(R.id.editLong);

        orgManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);


        try {
            gps_enabled = orgManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.i("gps_enabled", ex.toString());
        }
        try {
            network_enabled = orgManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.i("network_enabled", ex.toString());
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder builder = new Builder(
                    HelloAndroidGpsActivity.this);
            builder.setTitle("Attention!");
            builder.setMessage("Sorry, location is not determined. Please enable location providers");
            builder.setPositiveButton("OK",
                    HelloAndroidGpsActivity.this);
            builder.setNeutralButton("Cancel",
                    HelloAndroidGpsActivity.this);
            builder.create().show();
        }


        Criteria criteria = new Criteria();
        bestProvider = orgManager.getBestProvider(criteria, false);
        orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
        Location location = orgManager.getLastKnownLocation(bestProvider);

        if (location!=null){
            setLat.setText("Latitude:" + currLatitude);
            setLong.setText("Longitude:" + currLongtitude);
            originLocation.setLatitude(currLatitude);
            originLocation.setLongitude(currLongtitude);
        }
        //else Toast.makeText(getBaseContext(), "Error in GPS", Toast.LENGTH_SHORT).show();

        setDest.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {


                destLat.setText("Lat:"+editLat.getText().toString().trim());
                destLong.setText("Long"+editLong.getText().toString().trim());

                destLatitude = Double.parseDouble(String.valueOf(editLat.getText().toString().trim()));
                destLongtitude = Double.parseDouble(String.valueOf(editLong.getText().toString().trim()));

                destinationLocation.setLatitude(destLatitude);
                destinationLocation.setLongitude(destLongtitude);

                float distance = originLocation.distanceTo(destinationLocation);
                tjd.setText(String.valueOf(distance/1000)+ " Kms ");

            }
        });
    }

    /** Register for the updates when Activity is in foreground */
    @Override
    protected void onResume() {
        super.onResume();
        orgManager.requestLocationUpdates(bestProvider, 60000, 1, this);
    }

    /** Stop the updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        orgManager.removeUpdates(this);
    }

    public void onClick(DialogInterface dialog, int which) {
        if (which == DialogInterface.BUTTON_NEUTRAL) {
            setLat.setText("Sorry, location is not determined. To fix this please enable location providers");
        } else if (which == DialogInterface.BUTTON_POSITIVE) {
            startActivity(new Intent(
                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null) {
            // This needs to stop getting the location data and save the
            // battery power.
            //orgManager.removeUpdates(orgListener);

            currLatitude = location.getLatitude();
            currLongtitude = location.getLongitude();

            currLocation.setLatitude(currLatitude);
            currLocation.setLongitude(currLongtitude);

            currLat.setText(String.valueOf(currLatitude));
            currLong.setText(String.valueOf(currLongtitude));

            float fromhome = originLocation.distanceTo(currLocation);

            float toward = currLocation.distanceTo(destinationLocation);

            HelloAndroidGpsActivity.this.fromhome.setText(String.valueOf(fromhome/1000)+ " Kms ");
            HelloAndroidGpsActivity.this.toward.setText(String.valueOf(toward/1000) + " Kms ");

            if (toward/1000 <= 14 ){

                Toast.makeText(getBaseContext(), "You are "+ toward/1000 + " Kms towards Destination ", Toast.LENGTH_SHORT).show();
            }
        }
    }


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

    }

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

    }

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

    }
}

I know this kind of question has been million times.我知道这种问题已经被问过百万次了。 I have tried all methods which has been specified in answers.我已经尝试了答案中指定的所有方法。 But i havent got any output.但我没有得到任何输出。 Please help.请帮忙。

You should not call requestLocationUpdates on onCreate as it is redundant since your code will call it on onResume.您不应在 onCreate 上调用 requestLocationUpdates,因为它是多余的,因为您的代码将在 onResume 上调用它。 The flow is onCreate --> onStart --> onResume.流程是 onCreate --> onStart --> onResume。

To get Current Location, this is working pretty fine with me check this out.要获取当前位置,这对我来说效果很好,请检查一下。

our Activity is like this我们的Activity是这样的


public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
/** Called when the activity is first created. */

private EditText showLocation;
private Button btnGetLocation;
private ProgressBar progress;

private LocationManager locManager;
private LocationListener locListener = new myLocationListener();

private boolean gps_enabled = false;
private boolean network_enabled = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    showLocation = (EditText) findViewById(R.id.txtShowLoc);
    showLocation.setEnabled(false);

    progress = (ProgressBar) findViewById(R.id.progressBar);
    progress.setVisibility(View.GONE);

    btnGetLocation = (Button) findViewById(R.id.btnGetLoc);
    btnGetLocation.setOnClickListener(this);

    locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    progress.setVisibility(View.VISIBLE);

    try{
        gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
    catch(Exception ex){            
    }
    try{
        network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);           
    }
    catch(Exception ex){

    }       

    if (!gps_enabled && !network_enabled) {
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("Attention!");
        builder.setMessage("Sorry, location is not determined. Please enable location providers");
        builder.setPositiveButton("OK", this);
        builder.setNeutralButton("Cancel", this);
        builder.create().show();
        progress.setVisibility(View.GONE);
    }

    if (gps_enabled) {
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
    }
    if (network_enabled) {
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
    }       
}

private class myLocationListener implements LocationListener{

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if(location!=null){

            locManager.removeUpdates(locListener);

            String Speed = "Device Speed: " +location.getSpeed();
            String longitude = "Longitude: " +location.getLongitude();
            String latitude = "Latitude: " +location.getLatitude();
            String altitiude = "Altitiude: " + location.getAltitude();
            String accuracy = "Accuracy: " + location.getAccuracy();
            String time = "Time: " + location.getTime();

            String cityName=null;

            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            //public List<Address> addresses= gcd.getFromLocation (double latitude1, double longitude1, int maxResults)


            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                if (addresses.size() > 0)
                    System.out.println(addresses.get(0).getLocality());
                cityName=addresses.get(0).getLocality();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            showLocation.setText("City Name: "+cityName+"\n"+Speed + "\n"+longitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
            progress.setVisibility(View.GONE);
        }
    }

    @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 void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    if(which == DialogInterface.BUTTON_NEUTRAL){
        showLocation.setText("location is not getting due to location provider");

    }
    else if (which == DialogInterface.BUTTON_POSITIVE){
        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

    }
}}

and main.xml is和 main.xml 是


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView android:id="@+id/textView1" android:layout_width="match_parent" android:text="My Location is:" android:textSize="25sp" android:layout_height="wrap_content"></TextView>
<EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.24" android:lines="5" android:id="@+id/txtShowLoc">
    <requestFocus></requestFocus>
</EditText>
<LinearLayout android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:layout_width="match_parent" android:gravity="center">
    <ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/progressBar"></ProgressBar>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center">
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Get Current Location" android:id="@+id/btnGetLoc"></Button>
</LinearLayout>


and my manifest file is我的清单文件是


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="rdc.getCurrentLocaion"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
    <activity android:name=".MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

let me know if you get any trouble!!如果您遇到任何麻烦,请告诉我!!

@Ramdhan Thanks for your code. @Ramdhan 感谢您的代码。 But i corrected a mistake made in my code.但是我更正了代码中的一个错误。

  Criteria criteria = new Criteria();
        bestProvider = orgManager.getBestProvider(criteria, false);
        orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
        Location location = orgManager.getLastKnownLocation(bestProvider);

    if (location!=null){
        setLat.setText("Latitude:" + currLatitude);
        setLong.setText("Longitude:" + currLongtitude);
        originLocation.setLatitude(currLatitude);
        originLocation.setLongitude(currLongtitude);
    } 

Cheanged code:修改后的代码:

if (location != null) {
        setLat.setText("Latitude:" + location.getLatitude());
        setLong.setText("Longitude:" + location.getLongitude());
        originLocation.setLatitude(location.getLatitude());
        originLocation.setLongitude(location.getLongitude());
    }

For requesting location update from OnCreate Methode用于从 OnCreate Methode 请求位置更新

LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener=new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    } if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 请求按网络更新位置的问题 - Problem requesting location updates by network 检查Android应用程序LocationClient是否正在请求位置更新 - Check if Android app LocationClient is requesting location updates 检查Android应用是否正在请求位置更新 - Check if Android app is requesting location updates 请求位置更新超过5秒(Android融合位置) - Requesting location updates more often than 5 seconds (Android Fused location) 在融合位置的帮助下请求位置更新时,应用程序崩溃 - App Crashes While Requesting Location Updates With The Help Of Fused Location Android:在Android模拟器中请求位置更新后,应用停止运行 - Android: App stops working after requesting location updates in android simulator 正在主动运行Google Maps Navigation时请求位置更新 - Requesting location updates while Google Maps Navigation is actively running 使用FusedLocationProviderClient请求位置更新不起作用,永远不会调用回调 - Requesting location updates using FusedLocationProviderClient is not working, callback is never called Android中的位置更新requestLocationUpdates方法 - Location Updates in Android requestLocationUpdates method 使用Firebase时,ListView仅在onCreate()方法中更新 - ListView updates only in onCreate() method when using Firebase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM