(使用位置管理器)的GPS坐标获得打印成空 [英] GPS coordinates (using location manager) get printed as null

查看:131
本文介绍了(使用位置管理器)的GPS坐标获得打印成空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OnCreateMethod,

OnCreateMethod,

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


LocationListener listener = new LocationListener() {

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

        }

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

        }

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

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            coordinates = new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()).toString();

        }
    };
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

}

,当我尝试显示在一个TextView坐标(的setText),它说空

and when i try to show coordinates (setText) in a TextView, it says "null"

Android清单,

Android Manifest,

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

尽管我的TextView显示空,我得到我的状态栏通知它说搜索GPS

Even though my TextView displays "null", i get a notification on my status bar which says "Searching for GPS"

推荐答案

下面是我的方法:

这是因为全球定位系统锁定等需要时间,你不想陷入瘫痪你的主UI线程。使用异步任务将使你扔一个进程在后台自动更新用户界面领域,一旦方法有效执行。

This is because GPS locking etc takes time and you don't want to bog down your main UI thread. Using a asynch task will enable you to throw a process in the background and auto update the UI field once the method has effectively executed.

下面是一个code段:对于做的非同步任务的背景部分

Here is a code snippet: For the do in background part of the Asynch task

protected String doInBackground(Location... params) {
        /*
         * Get a new geocoding service instance, set for localized addresses.
         * This example uses android.location.Geocoder, but other geocoders that
         * conform to address standards can also be used.
         */
        // Show user progress bar
        pd.show();      
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

        // Get the current location from the input parameter list
        Location location = params[0];

        // Create a list to contain the result address
        List<Address> addresses = null;

        // Try to get an address for the current location. Catch IO or network
        // problems.
        try {

            /*
             * Call the synchronous getFromLocation() method with the latitude
             * and longitude of the current location. Return at most 1 address.
             */
            addresses = geocoder.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1);

            // Catch network or other I/O problems.
        } catch (IOException exception1) {

            // Log an error and return an error message
            Log.e(LocationUtils.APPTAG,
                    mContext.getString(R.string.IO_Exception_getFromLocation));

            // print the stack trace
            exception1.printStackTrace();

            // Return an error message
            return (mContext.getString(R.string.IO_Exception_getFromLocation));

            // Catch incorrect latitude or longitude values
        } catch (IllegalArgumentException exception2) {

            // Construct a message containing the invalid arguments
            String errorString = mContext.getString(
                    R.string.illegal_argument_exception,
                    location.getLatitude(), location.getLongitude());
            // Log the error and print the stack trace
            Log.e(LocationUtils.APPTAG, errorString);
            exception2.printStackTrace();

            //
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {

            // Get the first address
            Address address = addresses.get(0);

            // Format the first line of address
            addressText = mContext.getString(
                    R.string.address_output_string,

                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",

                    // Locality is usually a city
                    address.getLocality(),

                    // The country of the address
                    address.getCountryName());

            // Return the text
            return addressText;

            // If there aren't any addresses, post a message
        } else {
            return mContext.getString(R.string.no_address_found);
        }
    }

在后台任务执行结束后,你可以运行一个onPostExecute方法。

After the background task has finished executing you can run a onPostExecute method.

protected void onPostExecute(String  result) {
        delegate.processFinished(result);
        // Update the EditText on the UI Thread.
        ed.setText(result);
        // Hide progress bar    
        pd.hide();
    }

在相关主类,你可以调用的Aysch任务,并要求它来显示结果。

public void getAddress(View v) {
        // In Gingerbread and later, use Geocoder.isPresent() to see if a
        // geocoder is available.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
                && !Geocoder.isPresent()) {
            // No geocoder is present. Issue an error message
            Toast.makeText(getActivity(), R.string.no_geocoder_available,
                    Toast.LENGTH_LONG).show();
            return;
        }

        if (servicesConnected()) {
            // Get the current location
            Location currentLocation = mLocationClient.getLastLocation();
            Lat = currentLocation.getLatitude();
            Lng = currentLocation.getLongitude();
            LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
            // Message to show results 
            Toast.makeText(getActivity(), LatLng, 0).show();

            // Turn the indefinite activity indicator on
            // Start the background task
            GetAddressTask getAddressTask = new GetAddressTask(getActivity(),
                    locationAddress, pd);
            getAddressTask.delegate = this;
            getAddressTask.execute(currentLocation);

        } else {
            Toast.makeText(getActivity(), "servicesConnected() == false",
                    Toast.LENGTH_SHORT).show();
        }
    }

请注意:这只是你所需要的相关code片段。请参阅我的 github上如果您需要更详细的办法。别忘了upvote和接受的答案

Note: this is only the relevant code snippets you need. Refer to my github if you require more detailed approach. Don't forget to upvote and accept answer!

我包括一对夫妇的应用程序,我做了说明什么code能做到不用担心地图和东西的照片。这只是表明我已经加入并与朋友谁通过谷歌云服务器。

I included a couple of pictures of an app I made to illustrate what the code can do don't worry about the map and stuff. It just shows events I have added and shared with friends who have the same app on their phone via a Google Cloud Server.

这篇关于(使用位置管理器)的GPS坐标获得打印成空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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