有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法获取gps位置

我不知道为什么,但我无法获得GPS位置。。。 lm.getLastKnownLocation始终返回null,并且从不调用onLocationChanged。 但我可以在系统托盘上看到gps图标

有什么想法吗

package com.localfotos;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import 安卓.content.Context;
import 安卓.graphics.Bitmap;
import 安卓.graphics.BitmapFactory;
import 安卓.graphics.Canvas;
import 安卓.graphics.Matrix;
import 安卓.graphics.Paint;
import 安卓.location.Location;
import 安卓.location.LocationListener;
import 安卓.location.LocationManager;
import 安卓.os.Bundle;
import 安卓.os.Handler;
import 安卓.service.wallpaper.WallpaperService;
import 安卓.util.Log;
import 安卓.view.MotionEvent;
import 安卓.view.SurfaceHolder;



/*
 * This animated wallpaper draws a rotating wireframe cube.
 */
public class MyWallpaperService extends WallpaperService implements LocationListener{

    private final String TAG = "WallpaperService============================";
    private LocationManager lm;
    private final Handler mHandler = new Handler();


    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "got location!");

    }

    @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 onCreate() {
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(this);
    }

    @Override
    public Engine onCreateEngine() {
        return new CubeEngine(this);
    }


    class CubeEngine extends Engine{

        MyWallpaperService mws;

        private final Runnable mDrawCube = new Runnable() {
            public void run() {
                drawFrame();
            }
        };
        private boolean mVisible;
        private double lat = -1;
        private double lon = -1;

        CubeEngine(MyWallpaperService mymws) {
            mws = mymws;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mHandler.removeCallbacks(mDrawCube);
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            mVisible = visible;
            if (visible) {
                drawFrame();
            } else {
                mHandler.removeCallbacks(mDrawCube);
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            drawFrame();
        }

        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
        }

        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            mVisible = false;
            mHandler.removeCallbacks(mDrawCube);
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset,
                float xStep, float yStep, int xPixels, int yPixels) {
            drawFrame();
        }

        /*
         * Store the position of the touch event so we can use it for drawing later
         */
        @Override
        public void onTouchEvent(MotionEvent event) {
            super.onTouchEvent(event);
        }

        /*
         * Draw one frame of the animation. This method gets called repeatedly
         * by posting a delayed Runnable. You can do any drawing you want in
         * here. This example draws a wireframe cube.
         */
        void drawFrame() {
            final SurfaceHolder holder = getSurfaceHolder();

            Canvas c = null;
            try {
                c = holder.lockCanvas();
                if (c != null) {
                    // draw something
                    drawCube(c);
                }
            } finally {
                if (c != null) holder.unlockCanvasAndPost(c);
            }

            // Reschedule the next redraw
            mHandler.removeCallbacks(mDrawCube);
            if (mVisible) {
                mHandler.postDelayed(mDrawCube, 1000 * 10);
            }
        }

        /*
         * Draw a wireframe cube by drawing 12 3 dimensional lines between
         * adjacent corners of the cube
         */

        //taken from http://p-xr.com/安卓-tutorial-how-to-parse-read-json-data-into-a-安卓-listview/
        private JSONObject getJSONfromURL(String url){

            //initialize
            InputStream is = null;
            String result = "";
            JSONObject jArray = null;

            //http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
            }

            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
            }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
            }

            //try parse the string to a JSON object
            try{
                    jArray = new JSONObject(result);
            }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
            }

            return jArray;
        }


        String getPanoramioUrl(double minx, double maxx, double maxy, double miny){
            return "http://www.panoramio.com" +
                    "/map/get_panoramas.php?" +
                    "set=public&from=0&to=1&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy;
        }

        void drawCube(Canvas canvas) {
            //canvas.save();
            //canvas.translate(0, 0);
            //c.drawColor(0xff00aa00);

            Location loc = mws.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            try{
                if (lat == loc.getLatitude() && lon == loc.getLongitude()){
                    return;
                }
            }catch(NullPointerException exc){
                Log.d(TAG, "gps not ready");
                return;
            }
            lat = loc.getLatitude();
            lon = loc.getLongitude();

        }


    }
}

<application 安卓:icon="@drawable/icon" 安卓:label="@string/app_name">

    <service 安卓:name=".MyWallpaperService"
        安卓:label="@string/app_name"
        安卓:icon="@drawable/icon"
        安卓:permission="安卓.permission.BIND_WALLPAPER">

        <intent-filter>
            <action 安卓:name="安卓.service.wallpaper.WallpaperService" />
        </intent-filter>
        <meta-data 安卓:name="安卓.service.wallpaper"
            安卓:resource="@xml/livewallpaper" />

    </service>

</application>


共 (1) 个答案

  1. # 1 楼答案

    你需要补充

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

    使用GPS。要使用网络位置,请使用:

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

    我想这对你有用