【问题标题】:Can't get location on android studio无法在 android studio 上获取位置
【发布时间】:2015-12-09 12:34:06
【问题描述】:

我尝试了几天来获取我在 android studio 上的当前位置,但我总是得到一个空位置。我已经尝试了很多这样的解决方案:I can't get location on Android real phone 或这个:getlastknownlocation always return null after I re-install the apk file via eclipse 但这不起作用......我已经像这样在 Android 设备监视器上管理了位置:

并且在虚拟设备中启用了 GPS……它在我的手机上也无法使用。所以这是我的代码

public class MyLocation {
private double longitude;
private double latitude;
private LocationManager locationManager;
private Context context;
private LocationListener locationListener; 

public MyLocation(Context context){
    this.context = context;
    this.locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
}
public void findLocation() {
        String location_context = context.LOCATION_SERVICE;
        locationManager = (LocationManager) context.getSystemService(location_context);

        List<String> providers = locationManager.getProviders(true);

        for (String provider : providers) {
            try {
                Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                }
                locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
    }

public double getLongitude() {
    return longitude;
}

public void setLongitude(double longitude) {
    this.longitude = longitude;
}

public double getLatitude() {
    return latitude;
}

public void setLatitude(double latitude) {
    this.latitude = latitude;
}

提前非常感谢

编辑:我忘了说我在清单中有权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

编辑:这是我的活动

public class CameraActivity extends Activity implements SingleLocationProvider.OnLocationProviderListener {
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private ImageView imageView;
    private Button backButton;
    private Button sendButton;
    private Picture picture;
    private TextView title;
    private TextView comment;
    private String email;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        picture = new Picture();
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            email = extras.getString("email");
        }
        else{
            email = "no email";
        }
        setContentView(R.layout.activity_camera);
        title = (EditText) findViewById(R.id.title);
        title.setText("comments");
        comment = (EditText) findViewById(R.id.comment);
        comment.setText("test");
        imageView = (ImageView) findViewById(R.id.imageView);
        backButton = (Button) findViewById(R.id.backButton);
        sendButton = (Button) findViewById(R.id.sendButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickBackButton(v);
            }
        });
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSendButton(v);
            }
        });

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setDrawingCacheEnabled(true);
            imageView.buildDrawingCache(true);
            imageView.setImageBitmap(imageBitmap);
            imageView.setDrawingCacheEnabled(false);
        }
        else if(requestCode == 2 && resultCode == 2){
            title.setText("");
            comment.setText("");
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
        else{
            backToPreviousActivity();
        }
    }

    private void backToPreviousActivity(){
        Intent intent = new Intent(this, ConnectionActivity.class);
        //Clear all the activities
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickBackButton(View view) {
        Intent intent = new Intent(this, ConnectionActivity.class);
        //Clear all the activities
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickSendButton(View view) {
        if(comment.getText().toString().isEmpty() || title.getText().toString().isEmpty()){
            Toast.makeText(this, R.string.errorSendPicture, Toast.LENGTH_LONG)
                    .show();
        }else {
            imageView.buildDrawingCache();
            Bitmap bmap = imageView.getDrawingCache();
            String stringImage = BitmapToString(bmap);
            setGpsCoordinates(picture);
            picture.setPictureString(stringImage);
            picture.setEmailPerson(email);
            picture.setComment(comment.getText().toString());
            picture.setName(title.getText().toString());
            //sendPicture();
            new HttpRequestTask().execute();
        }
    }



    private class HttpRequestTask extends AsyncTask<Void, Void, HttpResponse> {
        //private void sendPicture() {
        @Override
        protected HttpResponse doInBackground(Void... params) {
            RestTemplate restTemplate = new RestTemplate();
            final String url = "http://192.168.128.13:8081/DumontPerat/sharesite/picture/";
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setHeader("content-type", "application/json; charset=UTF-8");

            JSONObject dato = new JSONObject();
            try {
                dato.put("name", picture.getName());
                dato.put("pictureString", picture.getPictureString());
                dato.put("comment", picture.getComment());
                dato.put("emailPerson", picture.getEmailPerson());
                StringEntity entity = new StringEntity(dato.toString());
                post.setEntity(entity);
                HttpResponse resp = httpClient.execute(post);
                return resp;
            } catch (JSONException ex) {
            } catch (UnsupportedEncodingException ex) {
            } catch (IOException ex) {
            } catch (Exception e) {
                Log.e("ConnectionActivity", e.getMessage(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(HttpResponse response) {
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                goToLastActivity();
            }
            else{
                createToastProblem();
            }
        }
    }

    private void goToLastActivity(){
        Intent intent = new Intent(this, LastActivity.class);
        startActivityForResult(intent, 2);
    }

    private void setGpsCoordinates(Picture picture){
        /*MyLocation myLocation = new MyLocation(this.getApplicationContext());
        myLocation.findLocation();
            picture.setLatitude((float) myLocation.getLatitude());
            picture.setLongitude((float) myLocation.getLongitude());*/
        try {
            SingleLocationProvider mLocationProvider = new SingleLocationProvider(this);
            mLocationProvider.setOnLocationProviderListener(this);
            mLocationProvider.setTimeout(20000);
            mLocationProvider.requestLocation();
            Location l = mLocationProvider.getLastKnownLocation();
            if(l != null) {
                picture.setLatitude((float) l.getLatitude());
                picture.setLongitude((float) l.getLongitude());
            }
        }catch(Exception ex){}
    }

    private void createToastProblem(){
        Toast.makeText(this, R.string.errorConnection, Toast.LENGTH_LONG).show();
    }

    private String BitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String temp = Base64.encodeToString(b, Base64.DEFAULT);
        return temp;
    }

    @Override
    public void onLocationStartedSeeking() {

    }

    @Override
    public void onLocationStoppedSeeking() {

    }

    @Override
    public void onLocationFound(Location location) {
        picture.setLatitude((float) location.getLatitude());
        picture.setLongitude((float) location.getLongitude());
    }

    @Override
    public void onLocationNotFound() {

    }

    @Override
    public void onGPSProviderDisabled() {

    }
}

编辑:好的,我很愚蠢,该位置一直在工作......我忘记将我的信息发送到我的 Rest 服务,这就是为什么我的纬度和经度总是 0......太愚蠢了......谢谢你们!

【问题讨论】:

标签: android android-studio gps location


【解决方案1】:

好吧,我傻了,位置一直都在工作...我忘记将我的信息发送到我的 Rest 服务,这就是为什么我的纬度和经度总是 0... 太愚蠢了.. 谢谢大家!

【讨论】:

    【解决方案2】:
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    @SuppressWarnings("ResourceType")
    public class SingleLocationProvider {
    
        private int mTimeout = 5000;
        private LocationManager mLocationManager;
        private SingleLocationListener mListener;
        private Location mLastKnownLocation;
    
        private Timer mTimer;
        private RequestTimerTask mTimerTask;
    
        private OnLocationProviderListener mCallback;
    
        public SingleLocationProvider(Context context) {
            mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            mListener = new SingleLocationListener();
    
            mTimer = new Timer();
            mTimerTask = new RequestTimerTask();
        }
    
        public void requestLocation() {
            startSeeking();
        }
    
        public boolean checkGPSProviderEnabled() {
            if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                if (mCallback != null) {
                    mCallback.onGPSProviderDisabled();
                }
    
                return false;
            }
    
            return true;
        }
    
        public void cancel() {
            stopSeeking();
        }
    
        private void startSeeking() {
            if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                if (mCallback != null) {
                    mCallback.onGPSProviderDisabled();
                    return;
                }
            }
    
            if (mCallback != null){
                mCallback.onLocationStartedSeeking();
            }
    
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Integer.MAX_VALUE, Integer.MAX_VALUE, mListener);
    
            mTimer.schedule(mTimerTask, mTimeout);
        }
    
        private void stopSeeking() {
            mLocationManager.removeUpdates(mListener);
    
            mTimer.purge();
            mTimer.cancel();
    
            if (mCallback != null){
                mCallback.onLocationStoppedSeeking();
            }
        }
    
        public void setTimeout(int timeout) {
            mTimeout = timeout;
        }
    
        public void setOnLocationProviderListener(OnLocationProviderListener callback) {
            mCallback = callback;
        }
    
        public Location getLastKnownLocation() {
            return mLastKnownLocation;
        }
    
        private class SingleLocationListener implements LocationListener {
    
            @Override
            public void onLocationChanged(Location location) {
                if (location != null) {
    
                    mLastKnownLocation = location;
    
                    if (mCallback != null) {
                        mCallback.onLocationFound(location);
                    }
    
                    stopSeeking();
                }
            }
    
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // Empty Block
            }
    
            @Override
            public void onProviderEnabled(String provider) {
                // Empty Block
            }
    
            @Override
            public void onProviderDisabled(String provider) {
                // Empty Block
            }
        }
    
        private class RequestTimerTask extends TimerTask {
    
            @Override
            public void run() {
                mLocationManager.removeUpdates(mListener);
    
                if (mCallback != null) {
                    mCallback.onLocationNotFound();
                }
    
                stopSeeking();
            }
        }
    
        public interface OnLocationProviderListener {
            void onLocationStartedSeeking();
    
            void onLocationStoppedSeeking();
    
            void onLocationFound(Location location);
    
            void onLocationNotFound();
    
            void onGPSProviderDisabled();
        }
    
    }
    

    这就是用法

    SingleLocationProvider mLocationProvider = new SingleLocationProvider(this);
    mLocationProvider.setOnLocationProviderListener(this);
    mLocationProvider.setTimeout(20000);
    mLocationProvider.requestLocation();
    

    将这些添加到您的清单以获得许可

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    您可以在真实设备上进行测试。 随意使用它:)

    希望对你有帮助。

    【讨论】:

    • 这条线不起作用:mLLocationProvider.setOnLocationProviderListener(this);,我试试这个(SingleLocationProvider.OnLocationProviderListener),但这也不起作用......
    • 只保留这一行和“mLocationProvider.setOnLocationProviderListener(this);”并让您的活动或类实现“SingleLocationProvider.OnLocationProviderListener”。
    • 虽然你有这行“mLocationProvider.setOnLocationProviderListener(this);” Alt + Enter 并选择 let the implement blah blah.
    • 试试这个,但是当我想得到位置时它仍然是空的...... :( 不知道怎么了......
    • 我希望你不要在你的“我的位置”课上这个课。您可以发布您的活动吗?
    【解决方案3】:

    您应该在清单文件中请求这些权限:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    【讨论】:

    • 我已经这样做了,但我忘了提及它(我编辑了我的帖子!)
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多