无法在Android Studio上获取位置 [英] Can't get location on android studio

查看:111
本文介绍了无法在Android Studio上获取位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了几天以获取我在android studio上的当前位置,但是我总是得到一个空位置.我已经尝试了很多类似此解决方案的方法:

I try for days to get my current location on android studio but I always get a null location. I already try lot of things like this solution : I can't get location on Android real phone or this one : getlastknownlocation always return null after I re-install the apk file via eclipse but that does not work... I have managed the location on the Android Device Monitor like this :

并且在虚拟设备中启用了GPS ...我的手机也无法正常工作.这是我的代码

And the GPS is enable in the virtual device... It's not working on my phone too. So this is my code

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;
}

非常感谢

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

EDIT : I forgot to say that I have the permissions in my manifest :

<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 ...如此愚蠢..谢谢你们所有人!

Ok, I'm stupid, the location has always been working... I forget to send my information to my Rest service it's why I was always 0 to the latitude and longitude... So stupid.. Thank you all !

推荐答案

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

Ok, I'm stupid, the location has always been working... I forget to send my information to my Rest service it's why I was always 0 to the latitude and longitude... So stupid.. Thank you all !

这篇关于无法在Android Studio上获取位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆