GVKun编程网logo

android 原生GPS定位(安卓原生定位)

6

在本文中,我们将为您详细介绍android原生GPS定位的相关知识,并且为您解答关于安卓原生定位的疑问,此外,我们还会提供一些关于Androidgpswifi基站定位集合、Androidgps定位、A

在本文中,我们将为您详细介绍android 原生GPS定位的相关知识,并且为您解答关于安卓原生定位的疑问,此外,我们还会提供一些关于Android gps wifi 基站 定位集合、Android gps 定位、Android GPS 定位的实现(1)、android gps 定位问题的有用信息。

本文目录一览:

android 原生GPS定位(安卓原生定位)

android 原生GPS定位(安卓原生定位)

package com.hzg.my_record;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Jay on 2015/8/28 0028.
 */
public class MyFragment4 extends Fragment {

    private Button btnStart;
    private Button btnStop;
    private TextView textView;
    private Location mLocation;
    private LocationManager mLocationManager;


    public MyFragment4() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_content,container,false);

        btnStart = (Button)view.findViewById(R.id.btnStart);
        btnStop = (Button)view.findViewById(R.id.btnStop);
        textView = (TextView)view.findViewById(R.id.txt_content);
        btnStart.setOnClickListener(btnClickListener); //开始定位
        btnStop.setOnClickListener(btnClickListener); //结束定位按钮

        return view;
    }

    public Button.OnClickListener btnClickListener = new Button.OnClickListener()
    {
        public void onClick(View v)
        {
            Button btn = (Button)v;
            if(btn.getId() == R.id.btnStart)
            {
                if(!gpsIsOpen())
                    return;

                mLocation = getLocation();

                if(mLocation != null)

                    textView.setText("维度:" + mLocation.getLatitude() + "\n经度:" + mLocation.getLongitude());
                else
                    textView.setText("获取不到数据");
            }
            else if(btn.getId() == R.id.btnStop)
            {
                mLocationManager.removeUpdates(locationListener);
            }

        }
    };

    private boolean gpsIsOpen()
    {
        boolean bRet = true;

        LocationManager alm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        if(!alm.isProviderEnabled(LocationManager.GPS_PROVIDER))
        {
            Toast.makeText(getActivity(), "未开启GPS", Toast.LENGTH_SHORT).show();
            bRet = false;
        }
        else
        {
            Toast.makeText(getActivity(), "GPS已开启", Toast.LENGTH_SHORT).show();
        }

        return bRet;
    }



    private Location getLocation()
    {
        //获取位置管理服务
        mLocationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

        //查找服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); //定位精度: 最高
        criteria.setAltitudeRequired(false); //海拔信息:不需要
        criteria.setBearingRequired(false); //方位信息: 不需要
        criteria.setCostAllowed(true);  //是否允许付费
        criteria.setPowerRequirement(Criteria.POWER_LOW); //耗电量: 低功耗

        String provider = mLocationManager.getBestProvider(criteria, true); //获取GPS信息

        Location location = mLocationManager.getLastKnownLocation(provider);

        mLocationManager.requestLocationUpdates(provider, 2000, 5, locationListener);

        return location;
    }

    private final LocationListener locationListener = new LocationListener()
    {
        public void onLocationChanged(Location location)
        {
            // TODO Auto-generated method stub
            if(location != null)
                textView.setText("维度:" + location.getLatitude() + "\n经度:"
                        + location.getLongitude());
            else
                textView.setText("获取不到数据");
        }

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

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

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

        }
    };
}

Android gps wifi 基站 定位集合

Android gps wifi 基站 定位集合

 

          其中GPS定位首先是GpsTask类异步返回GPS经纬度信息

GpsTask gpstask = new GpsTask(GpsActivity.this,new GpsTaskCallBack() {                        @Override                       
	public void gpsConnectedTimeOut() {                           
	gps_tip.setText("获取GPS超时了");                       
	}                       
	@Override                       
	public void gpsConnected(GpsData gpsdata) {                           
	do_gps(gpsdata);                       
	}                   
	}, 3000);          
	gpstask.execute();
           其中3000是设置获取gps数据timeout时间。GpsTask是根据
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
获取最后一次GPS信息,如果返回为Null则是根据监听获取Location信息发生改变时返回的GPS信息。因为手机获取GPS信息时间比较长,所以这个类实际使用时可能还存在一些BUG。 IAddressTask封装了获取地理位置的方法,具体代码如下:
 

	package com.maxtech.common.gps;

	import java.io.BufferedReader;
	import java.io.InputStreamReader;
	import org.apache.http.HttpEntity;
	import org.apache.http.HttpResponse;
	import org.json.JSONArray;
	import org.json.JSONObject;
	import android.app.Activity;
	import android.content.Context;
	import android.net.wifi.WifiManager;
	import android.telephony.TelephonyManager;
	import android.telephony.gsm.GsmCellLocation;

	public abstract class IAddressTask {
	        protected Activity context;

	        public IAddressTask(Activity context) {
	                this.context = context;
	        }

	        public abstract HttpResponse execute(JSONObject params) throws Exception;

	        public MLocation doWifiPost() throws Exception {
	                return transResponse(execute(doWifi()));
	        }

	        public MLocation doApnPost() throws Exception {
	                return transResponse(execute(doApn()));
	        }

	        public MLocation doGpsPost(double lat, double lng) throws Exception {
	                return transResponse(execute(doGps(lat, lng)));
	        }

	        private MLocation transResponse(HttpResponse response) {
	                MLocation location = null;
	                if (response.getStatusLine().getStatusCode() == 200) {
	                        location = new MLocation();
	                        HttpEntity entity = response.getEntity();
	                        BufferedReader br;
	                        try {
	                                br = new BufferedReader(new InputStreamReader(
	                                                entity.getContent()));
	                                StringBuffer sb = new StringBuffer();
	                                String result = br.readLine();
	                                while (result != null) {
	                                        sb.append(result);
	                                        result = br.readLine();
	                                }
	                                JSONObject json = new JSONObject(sb.toString());
	                                JSONObject lca = json.getJSONObject("location");
	                                location.Access_token = json.getString("access_token");
	                                if (lca != null) {
	                                        if (lca.has("accuracy"))
	                                                location.Accuracy = lca.getString("accuracy");
	                                        if (lca.has("longitude"))
	                                                location.Latitude = lca.getDouble("longitude");
	                                        if (lca.has("latitude"))
	                                                location.Longitude = lca.getDouble("latitude");
	                                        if (lca.has("address")) {
	                                                JSONObject address = lca.getJSONObject("address");
	                                                if (address != null) {
	                                                        if (address.has("region"))
	                                                                location.Region = address.getString("region");
	                                                        if (address.has("street_number"))
	                                                                location.Street_number = address
	                                                                                .getString("street_number");
	                                                        if (address.has("country_code"))
	                                                                location.Country_code = address
	                                                                                .getString("country_code");
	                                                        if (address.has("street"))
	                                                                location.Street = address.getString("street");
	                                                        if (address.has("city"))
	                                                                location.City = address.getString("city");
	                                                        if (address.has("country"))
	                                                                location.Country = address.getString("country");
	                                                }
	                                        }
	                                }
	                        } catch (Exception e) {
	                                e.printStackTrace();
	                                location = null;
	                        }
	                }
	                return location;
	        }

	        private JSONObject doGps(double lat, double lng) throws Exception {
	                JSONObject holder = new JSONObject();
	                holder.put("version", "1.1.0");
	                holder.put("host", "maps.google.com");
	                holder.put("address_language", "zh_CN");
	                holder.put("request_address", true);
	                JSONObject data = new JSONObject();
	                data.put("latitude", lat);
	                data.put("longitude", lng);
	                holder.put("location", data);
	                return holder;
	        }

	        private JSONObject doApn() throws Exception {
	                JSONObject holder = new JSONObject();
	                holder.put("version", "1.1.0");
	                holder.put("host", "maps.google.com");
	                holder.put("address_language", "zh_CN");
	                holder.put("request_address", true);
	                TelephonyManager tm = (TelephonyManager) context
	                                .getSystemService(Context.TELEPHONY_SERVICE);
	                GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
	                int cid = gcl.getCid();
	                int lac = gcl.getLac();
	                int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
	                int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
	                JSONArray array = new JSONArray();
	                JSONObject data = new JSONObject();
	                data.put("cell_id", cid);
	                data.put("location_area_code", lac);
	                data.put("mobile_country_code", mcc);
	                data.put("mobile_network_code", mnc);
	                array.put(data);
	                holder.put("cell_towers", array);
	                return holder;
	        }

	        private JSONObject doWifi() throws Exception {<br />        JSONObject holder = new JSONObject();        holder.put("version", "1.1.0");        holder.put("host", "maps.google.com");        holder.put("address_language", "zh_CN");        holder.put("request_address", true);                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);                if(wifiManager.getConnectionInfo().getBSSID() == null) {            throw new RuntimeException("bssid is null");        }                JSONArray array = new JSONArray();        JSONObject data = new JSONObject();        data.put("mac_address", wifiManager.getConnectionInfo().getBSSID());          data.put("signal_strength", 8);          data.put("age", 0);          array.put(data);        holder.put("wifi_towers", array);                return holder;    }        public static class MLocation {
	                public String Access_token;
	                public double Latitude;
	                public double Longitude;
	                public String Accuracy;
	                public String Region;
	                public String Street_number;
	                public String Country_code;
	                public String Street;
	                public String City;
	                public String Country;

	                @Override
	                public String toString() {
	                        StringBuffer buffer = new StringBuffer();
	                        buffer.append("Access_token:" + Access_token + "\n");
	                        buffer.append("Region:" + Region + "\n");
	                        buffer.append("Accuracy:" + Accuracy + "\n");
	                        buffer.append("Latitude:" + Latitude + "\n");
	                        buffer.append("Longitude:" + Longitude + "\n");
	                        buffer.append("Country_code:" + Country_code + "\n");
	                        buffer.append("Country:" + Country + "\n");
	                        buffer.append("City:" + City + "\n");
	                        buffer.append("Street:" + Street + "\n");
	                        buffer.append("Street_number:" + Street_number + "\n");
	                        return buffer.toString();
	                }
	        }
	} 

	 

 


 



转载:http://www.adobex.com/android/source/details/00000442.htm

Android gps 定位

Android gps 定位

我去,好久对没来 os 来了编辑器都有三种风格了,这愉快的周末即将开始,下午了,来个 gps 是如何定位的,Android 版本的,ios 的请绕走。

首先还是需要引入你的权限,在AndroidManifest.xml里加上这几个
<!--网络 精确定位gps,权限不懂的Google或者看API-->
<uses-permission android:name="android.permission.INTERNET"/>

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

权限都加上了,看看我的 activity

package*********
import***********
public class LocationActivity extends Activity {
    private String TAG = "LocationActivity";
    private  LocationManager locationManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    }
    @Override
    protected void onResume() {
        super.onResume();
        initData();//init
    }
    private void initData(){
        if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Log.i(TAG,"gps close");    
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            return;
        } else {
            Log.i(TAG,"gps open");
        }
        String bestProvider = locationManager.getBestProvider(getCriteria(),true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        updateView(location);
        /*
            1000毫秒  0米偏移量,更新,定位方式我用的NETWORK_PROVIDER,
            也可以用GPS_PROVIDER,只是gps在室内好像定不了
        */
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
        10000, locationListener);
    }
    private void updateGps(Location location) {
        if (location != null) {
         
            Log.i(TAG,"设备位置信息,经度:"+String.valueOf(location.getLongitude())
                        + "纬度:" + String.valueOf(location.getLatitude())
                        + "海拔:" + String.valueOf(location.getAltitude()));
        } else {
            Log.i(TAG,"暂时未获取到位置");
        }
    }
    private Criteria getCriteria() {
        Criteria criteria = new Criteria();
        /*
        设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,
        Criteria.ACCURACY_FINE则比较精细,此处注意,
        如果想粗略的定位要去AndroidManifest.xml中加上粗略的权限,
        */ 
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        // 设置是否需要方位信息
        criteria.setBearingRequired(false);
        // 设置是否需要海拔信息
        criteria.setAltitudeRequired(true);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }
    private LocationListener locationListener = new LocationListener() {
    
        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            updateGps(location);
            
        }
    
        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                // GPS状态为可见时
                case LocationProvider.AVAILABLE:
                    Log.i(TAG, "当前GPS状态为可见状态");
                    break;
                // GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
                    Log.i(TAG, "当前GPS状态为服务区外状态");
                    break;
                // GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    Log.i(TAG, "当前GPS状态为暂停服务状态");
                    break;
            }
        }
    
        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
            Location location = locationManager.getLastKnownLocation(provider);
            updateGps(location);
        }
    
        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
            updateGps(null);
        }
    
    };
    
    private GpsStatus.Listener listener = new GpsStatus.Listener() {

        @Override
        public void onGpsStatusChanged(int event) {
            switch (event) {
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    Log.i(TAG, "第一次定位");
                    break;
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    Log.i(TAG, "卫星状态改变");
                    GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
                            .iterator();
                    int count = 0;
                    while (iters.hasNext() && count <= maxSatellites) {
                        GpsSatellite s = iters.next();
                        count++;
                    }
                    break;
                case GpsStatus.GPS_EVENT_STARTED:
                    Log.i(TAG, "定位启动");
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    Log.i(TAG, "定位结束");
                    break;
            }
        }
    };
}

复制到你类中,有需要 import 的全部导入即可,运行下查看是否可以获取 gps,亲测三星是可以的,比较仓促,不足之处留言。

Android GPS 定位的实现(1)

Android GPS 定位的实现(1)

今天弄了一个多小时,写了一个GPS获取地理位置代码的小例子,包括参考了网上的一些代码,并且对代码进行了一些修改,希望对大家的帮助。具体代码如下:  要实用Adnroid平台的GPS设备,首先需要添加上权限,所以需要添加如下权限: 



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

具体实现代码如下:

首先判断GPS模块是否存在或者是开启:

复制代码
代码


    
    
    
private void openGPSSettings() { LocationManager alm = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); if (alm .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { Toast.makeText( this , " GPS模块正常 " , Toast.LENGTH_SHORT) .show(); return ; } Toast.makeText( this , " 请开启GPS! " , Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); startActivityForResult(intent, 0 ); // 此为设置完成后返回到获取界面 }

复制代码

如果开启正常,则会直接进入到显示页面,如果开启不正常,则会进行到GPS设置页面:

获取代码如下:

复制代码
代码


    
    
    
private void getLocation() { // 获取位置管理服务 LocationManager locationManager; String serviceName = Context.LOCATION_SERVICE; locationManager = (LocationManager) this .getSystemService(serviceName); // 查找到服务信息 Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度 criteria.setAltitudeRequired( false ); criteria.setBearingRequired( false ); criteria.setCostAllowed( true ); criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗 String provider = locationManager.getBestProvider(criteria, true ); // 获取GPS信息 Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置 updateToNewLocation(location); // 设置监听器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米 locationManager.requestLocationUpdates(provider, 100 * 1000 , 500 , locationListener);
}

复制代码

到这里就可以获取到地理位置信息了,但是还是要显示出来,那么就用下面的方法进行显示:

复制代码
代码


    
    
    
private void updateToNewLocation(Location location) { TextView tv1; tv1 = (TextView) this .findViewById(R.id.tv1); if (location != null ) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); tv1.setText( " 维度: " + latitude + " \n经度 " + longitude); } else { tv1.setText( " 无法获取地理信息 " ); } }

复制代码

这样子就能获取到当前使用者所在的地理位置了,至少如何下地图上实现,在下面将进行获取,并显示出来!对参考代码的人表示感谢!

android gps 定位问题

android gps 定位问题

package com.android.gps;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class GPSActivity extends Activity {
    /** Called when the activity is first created. */
	TextView gps;
    
    double latitude = 0.0;
    double longitude = 0.0;	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        gps = (TextView)findViewById(R.id.gps);//这个是一个textview用来显示当前的经纬度

        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        		if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){

        			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
 
        			if(location != null){
//        				latitude = location.getLatitude();
//        				longitude = location.getLongitude();
//        				String address = "your address is: "+Double.toString(latitude)+Double.toString(longitude);
//        				gps.setText(address);
        			
        			}
        		}else{

	
        			LocationListener locationListener = new LocationListener() {
        				
        				// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        				@Override
        				public void onStatusChanged(String provider, int status, Bundle extras) {
        					Toast.makeText(getApplicationContext(), "changed", Toast.LENGTH_SHORT).show();
        				}
        				
        				// Provider被enable时触发此函数,比如GPS被打开
        				@Override
        				public void onProviderEnabled(String provider) {
        					Toast.makeText(getApplicationContext(), "ENABLE", Toast.LENGTH_SHORT).show();

        				}
        				
        				// Provider被disable时触发此函数,比如GPS被关闭 
        				@Override
        				public void onProviderDisabled(String provider) {
        					Toast.makeText(getApplicationContext(), "DISABLE", Toast.LENGTH_SHORT).show();

        				}
        				
        				//当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发 
        				@Override
        				public void onLocationChanged(Location location) {
        					if (location != null) {   
        						latitude = location.getLatitude();
                				longitude = location.getLongitude();
                				String address = "your address is: "+Double.toString(latitude)+Double.toString(longitude);
                				gps.setText(address);
        					}
        				}
        			};
        			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener);   
        			Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);   
        			if(location != null){   
        				latitude = location.getLatitude(); //经度   
        				longitude = location.getLongitude(); //纬度
        				String address = "your address is: "+Double.toString(latitude)+Double.toString(longitude);
        				gps.setText(address);        				
        			}   
        		}
        
        
    }
}

为什么我的程序不能显示位置?真机或者模拟器都不行,如果把

        				latitude = location.getLatitude(); //经度   
        				longitude = location.getLongitude(); //纬度
        				String address = "your address is: "+Double.toString(latitude)+Double.toString(longitude);
        				gps.setText(address);   

这段代码放在 if (location != null) 前面 ,直接报错:GPS 已停止运行!

关于android 原生GPS定位安卓原生定位的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Android gps wifi 基站 定位集合、Android gps 定位、Android GPS 定位的实现(1)、android gps 定位问题的相关信息,请在本站寻找。

本文标签: