Android 位置未在真实设备中显示

Posted

技术标签:

【中文标题】Android 位置未在真实设备中显示【英文标题】:Android location not shown in real device 【发布时间】:2014-02-21 05:24:47 【问题描述】:

我正在创建一个应用程序来查找用户的当前位置。 我提到了这个链接 What is the simplest and most robust way to get the user's current location on android?

创建我的应用程序。 我的问题我对这两个提供者都进行了尝试,但它没有检测到任何提供者,结果总是 location=null 返回。 为什么会出现这个问题以及如何在手机中获取位置。? 提前谢谢...

我的代码放在这里 这是 MyLocation.java 类

package com.example.locationupadates;

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MyLocation 
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        trygps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Log.v("Ansar",""+"Network Enabled");catch(Exception ex)
        trynetwork_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        Log.v("Ansar",""+"Network Enabled");catch(Exception ex)

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
             Log.v("Ansar",""+"Not anything Enabled");
            return false;
        
        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
            Log.v("Ansar",""+"Location Listener Gps");
         if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
            Log.v("Ansar",""+"Location Listener Network");
          timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    

    LocationListener locationListenerGps = new LocationListener() 
        public void onLocationChanged(Location location) 
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
            Log.v("Ansar",""+location.getLongitude());
        
        public void onProviderDisabled(String provider) 
        public void onProviderEnabled(String provider) 
        public void onStatusChanged(String provider, int status, Bundle extras) 
    ;

    LocationListener locationListenerNetwork = new LocationListener() 
        public void onLocationChanged(Location location) 
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        
        public void onProviderDisabled(String provider) 
        public void onProviderEnabled(String provider) 
        public void onStatusChanged(String provider, int status, Bundle extras) 
    ;

    class GetLastLocation extends TimerTask 
        @Override
        public void run() 
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null)
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             

             if(gps_loc!=null)
                 locationResult.gotLocation(gps_loc);
                 return;
             
             if(net_loc!=null)
                 locationResult.gotLocation(net_loc);
                 return;
             
             locationResult.gotLocation(null);
        
    

    public static abstract class LocationResult
        public abstract void gotLocation(Location location);
    

MainActivity.java

package com.example.locationupadates;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

import com.example.locationupadates.MyLocation.LocationResult;

public class MainActivity extends Activity 
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         tv=(TextView) findViewById(R.id.tv);
         Log.d("Ansar",""+"oncreate");
        LocationResult locationResult = new LocationResult()
            @Override
            public void gotLocation(Location location)
                Log.v("Ansar",""+location.getLongitude());
               tv.setText("location:"+location+"latitude: "+location.getLatitude()+"longitude "+location.getLongitude()); 
            
        ;
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(this, locationResult);

    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    


Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationupadates"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.locationupadates.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

异常

02-21 11:39:05.963: W/dalvikvm(18909): threadid=11: thread exiting with uncaught exception (group=0x410e4390)
02-21 11:39:05.963: E/AndroidRuntime(18909): FATAL EXCEPTION: Timer-0
02-21 11:39:05.963: E/AndroidRuntime(18909): java.lang.NullPointerException
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MainActivity$1.gotLocation(MainActivity.java:23)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MyLocation$GetLastLocation.run(MyLocation.java:102)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at java.util.Timer$TimerImpl.run(Timer.java:284)
02-21 11:39:05.963: W/dalvikvm(18909): threadid=11: thread exiting with uncaught exception (group=0x410e4390)
02-21 11:39:05.963: E/AndroidRuntime(18909): FATAL EXCEPTION: Timer-0
02-21 11:39:05.963: E/AndroidRuntime(18909): java.lang.NullPointerException
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MainActivity$1.gotLocation(MainActivity.java:23)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MyLocation$GetLastLocation.run(MyLocation.java:102)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at java.util.Timer$TimerImpl.run(Timer.java:284)

【问题讨论】:

你能用 manifest.xml 和错误日志粘贴你的代码吗? 当我在我的设备三星中运行你的代码时,它完美地给了我想要的结果。我对提供者都进行了尝试,结果是肯定的,而不是错误。 Only the original thread that created a view hierarchy can touch its views 通常当您尝试从线程访问任何视图时会发生此错误。签入您的代码。将 Text 设置为 Textview 时出现此错误,对吗? 我在 HTC 设备上见过这类异常最多。 我在我的 Samsung S2、Android 4.1.2 中运行您的代码,它运行良好 :) 【参考方案1】:

试试下面的课……我想对你有帮助……

添加主要活动...

GPSTracker gps = new GPSTracker(ActivityNearBy.this);

if (gps.canGetLocation())  
  latitude = gps.getLatitude();
  longitude = gps.getLongitude();
 

GPS 服务

public class GPSTracker extends Service implements LocationListener 

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) 
    this.mContext = context;
    getLocation();


public Location getLocation() 
    try 

        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) 
            // no network provider is enabled

         else 
            this.canGetLocation = true;
            if (isNetworkEnabled) 
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) 
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) 
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    
                
            

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) 
                if (location == null) 
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) 
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) 
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        
                    
                
            
        

     catch (Exception e) 
        e.printStackTrace();
    

    return location;


/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() 
    if (locationManager != null) 
        locationManager.removeUpdates(GPSTracker.this);
    


/**
 * Function to get latitude
 * */
public double getLatitude() 
    if (location != null) 
        latitude = location.getLatitude();
    

    // return latitude
    return latitude;


/**
 * Function to get longitude
 * */
public double getLongitude() 
    if (location != null) 
        longitude = location.getLongitude();
    

    // return longitude
    return longitude;


/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() 
    return this.canGetLocation;


/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings",new DialogInterface.OnClickListener() 
        public void onClick(DialogInterface dialog, int which) 
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        
    );

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        public void onClick(DialogInterface dialog, int which) 
            dialog.cancel();
        
    );

    // Showing Alert Message
    alertDialog.show();


@Override
public IBinder onBind(Intent arg0) 
    // TODO Auto-generated method stub
    return null;


public void onLocationChanged(Location location) 
    // TODO Auto-generated method stub



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



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



@Override
public void onRebind(Intent intent) 
    // TODO Auto-generated method stub
    super.onRebind(intent);


@Override
public boolean onUnbind(Intent intent) 
    // TODO Auto-generated method stub
    return super.onUnbind(intent);


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

更新 ma​​nifest.xml

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

【讨论】:

我试过这个代码。实际上这段代码在模拟器上运行良好,但在设备上却不行。 请更新 Play 商店库并确保 GPS 开启或关闭。 此代码在 Play 商店(cqpon 应用程序)上的实时应用程序中运行良好

以上是关于Android 位置未在真实设备中显示的主要内容,如果未能解决你的问题,请参考以下文章

Facebook警告输入凭据未在真实设备IOS6上出现

某些图标未在某些 android 设备中显示

Android 推送通知横幅未在某些设备中显示

android - 谷歌地图未在某些设备上显示

屏幕关闭时,前台服务未在 Android 7.0+ 中接收位置更新

amp 应用程序横幅未在 android 和 IOS 设备中正常显示