2013-02-02 93 views
0

我想从GPS获取位置,但无法获取它。这是因为该位置是由网络提供商访问的。无法从GPS获取位置?

如果我评论网络提供商的所有代码,则GPS位置返回null。

我已经尝试了这么多,但无法解决此问题。

如果有人能帮上忙,那对我来说会很有帮助。

我使用这个链接引用..

https://stackoverflow.com/a/3145655/1395259

这里是我的代码:

MainActivity.java

package com.example.locationsimple; 

import com.example.locationsimple.MyLocation.LocationResult; 

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

public class MainActivity extends Activity { 

    TextView textView; 
    LocationResult locationResult; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     textView = (TextView) findViewById(R.id.textViewLocation); 
     Button button = (Button) findViewById(R.id.button); 
     button.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       locationResult = new LocationResult(){ 

        @Override 
        public void gotLocation(Location location) { 

         while(true) 
         { 
          Log.i("Log", "Inside while loop "); 

          if(location != null) 
          { 
           Log.i("Log", "Here the location is not null"); 
           if(location.getLatitude() !=0.0 || location.getLongitude() != 0.0) 
           { 
            if(location.getAccuracy() < 100) 
            { 
             Log.i("Log", "Inside while loop BREAKS"); 

             try 
             { 
              String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime(); 
              Log.i("Log",loc); 
              Toast.makeText(MainActivity.this, ""+loc, Toast.LENGTH_LONG).show(); 
              textView.setText(loc); 
             } 
             catch (Exception e) { 
              // TODO: handle exception 
              e.printStackTrace(); 
             } 

             break; 
            } 
            else 
            { 
             Log.i("Log", "no Accuracy"); 
             Log.i("Log", "latti"+location.getLatitude()+" Longi "+location.getLongitude()+" Accur "+location.getAccuracy()+location.getProvider());          
             break; 
            } 
           } 
          } 
          else 
          { 
           Log.i("Log", "Here got the location is null"); 
           break; 
          } 
         } 
         //textView.setText(location.getLatitude()+"::"+location.getLongitude()+"::"+location.getAccuracy()+" Provider "+location.getProvider());            
        } 
       }; 
       MyLocation myLocation = new MyLocation(); 
       myLocation.getLocation(MainActivity.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.activity_main, menu); 
     return true; 
    } 

} 

MyLocation.java

package com.example.locationsimple; 

import java.util.Timer; 
import java.util.TimerTask; 

import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.provider.Settings; 

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

    public boolean getLocation(Context context, LocationResult result) 
    { 
     mContext = context; 
     //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); 
      /*Criteria criteria = new Criteria(); 
      criteria.setAccuracy(Criteria.ACCURACY_HIGH); 
      lm.getBestProvider(criteria, true);*/ 
     //exceptions will be thrown if provider is not permitted. 
     try 
      { 
       gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
      } 
     catch(Exception ex) 
     { 
      ex.printStackTrace(); 
     } 
     try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){} 

     //don't start listeners if no provider is enabled 
     if(!gps_enabled || !network_enabled) 
     { 
      showSettingsAlert(); 
      return false; 
     }   
     if(gps_enabled) 
      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps); 
     if(network_enabled) 
      lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork); 
     timer1=new Timer(); 
     timer1.schedule(new GetLastLocation(), 30000); 
     return true; 
    } 
    public void showSettingsAlert(){ 


     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     alertDialog.setCancelable(false); 
     // Setting Dialog Title 
     alertDialog.setTitle("GPS Is Not Enabled"); 


     // Setting Dialog Message 
     alertDialog.setMessage("Please Enabled Wireless Network And GPS"); 

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

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    LocationListener locationListenerGps = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      timer1.cancel(); 
      locationResult.gotLocation(location); 
      lm.removeUpdates(this); 
      lm.removeUpdates(locationListenerNetwork); 
     } 
     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; 
      Location 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); 
    } 
} 

谢谢..

+0

请列出您的当前代码 –

+0

是的,确定队友! –

+0

@ Mr.Me问题已更新 –

回答

0

可以使用下面的服务,为越来越gps.just在开始时调用这个服务。

公共类的MyService延伸服务{

LocationManager locationManager; 
@Override 
public void onCreate() { 

    // 

     // TODO Auto-generated method stub 

     String context = Context.LOCATION_SERVICE; 
     locationManager = (LocationManager) getSystemService(context); 

     /** Criteria for selecting best provider */ 

     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     criteria.setAltitudeRequired(false); 
     criteria.setBearingRequired(false); 
     criteria.setCostAllowed(true); 
     criteria.setPowerRequirement(Criteria.POWER_LOW); 

     /** Passing criteria and select only enabled provider */ 
     String provider = locationManager.getBestProvider(criteria, true); 
     Location location = locationManager.getLastKnownLocation(provider); 
     /** calls the Location Listner */ 
     locationManager.requestLocationUpdates(provider, 500, 0,locationListener); 
    } 

    private final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      updateWithNewLocation(location); 
     } 

     public void onProviderDisabled(String provider) { 
      updateWithNewLocation(null); 
     } 

     public void onProviderEnabled(String provider) { 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 
    }; 

    private void updateWithNewLocation(Location location) 
    { 

     System.out.println("+++++++++++++++++++SASI+++++++++++++++++++++++++++++++++++++++++"); 
     String latLongString, addressString = null; 
     double lat = 0, lng = 0; 
     if (location != null) { 
      lat = location.getLatitude(); 
      lng = location.getLongitude(); 
      //latLongString = "Lat:" + lat + "\nLong: " + lng; 

      /** Getting Address */ 


     } else { 
      latLongString = "No location found"; 
      addressString = "No location found"; 
     } 
     //System.out.println("@@@@@@@@@@@" + addressString + lat + lng); 
     SearchDeals.latPoint=location.getLatitude(); 
     SearchDeals.lngPoint=location.getLongitude(); 




     Deals_route.sourcelati=location.getLatitude(); 
     Deals_route.sourcelong=location.getLongitude(); 

    } 




@Override 
public void onDestroy() { 

    super.onDestroy(); 

    // 

    //Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show(); 

    locationManager.removeUpdates(locationListener); 

    System.out.println("@@@@@@@@@@@ inside ONDESTROY GPS listener removed"); 

} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 

{ 

    // 

    Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()"); 

    //Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show(); 

    // We want this service to continue running until it is explicitly 

    // stopped, so return sticky. 

    return START_STICKY; 

} 




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

}

+0

您的意思是说如果我使用上面的代码,那么我不需要MyLocation类 –

+0

如何从Activity类调用service方法? –

+0

你只需要调用这个服务。试试看看结果 – DeepakAndroid

0

我刚刚测试了上面的代码我的设备上,一切都顺利运行,不知道什么是你的问题到底。

重要提示:

  • 请确保你在你的清单文件访问GPS定位权限

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

  • 的代码可能无法正常工作仿真器,更好地测试实际设备。如果你没有一个访问,请检出DMMS模拟器控制生成位置数据

编辑:

你需要提交了有关网络提供的位置数据。

并且还从LocationResult对象中删除textView.setText,因为textView为空。所以修正:

getLocation(Location location) { 
......... 
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime() +" "+location.getProvider(); 

Log.i("Log",loc); 
Toast.makeText(MainActivity.this, loc, Toast.LENGTH_LONG).show(); 
} 

,并从MyLocation类注释掉网络代码

// if(network_enabled) 

// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListenerNetwork);

+0

是你从GPS或网络获取位置。我的问题是我从提供商处获得位置。不是来自GPS。请回答问题 –

+0

我已经在menifest中添加了此权限。我的问题是,我无法从GPS获取位置。如果您从GPS提供商处获得位置,请回复... –

+0

经过测试和工作 –