无法在Android studio上

时间:2015-12-09 12:34:07

标签: android android-studio gps location

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

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

    }
}
编辑:好的,我是傻瓜,位置一直在工作......我忘记将我的信息发送到我的休息服务,这就是为什么我总是0到纬度和经度的原因。那么傻..谢谢大家!

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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" />

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

希望它有所帮助。

答案 2 :(得分:0)

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

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
相关问题