2016-11-16 20 views
1

私は、ボタンクリックでAndroidデバイスからgps経度と緯度を取得するLocationManagerを持っています。私の問題は、それが常に私に0.0を与えるということです。私はこれに何が間違っているのか分かりません。私はMyLocation.javaとAndroidManifest.xmlのパーミッションを与えました。また、gps信号があるかどうかを確認しました。Android LocationManagerには緯度と経度が0.0です

MyLocation.java

public class MyLocation 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 MyLocation(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) { 
       if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
         || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
       } 
       if (locationManager != null) { 
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
          || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        } 
        if (location != null) { 
         if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
           || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
          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){ 
     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
       || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      locationManager.removeUpdates(MyLocation.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 void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

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

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 

} 

tablelayout.java

public class tablelayout extends Activity implements View.OnClickListener { 
Button btn, btn2; 
MyLocation myLocation; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.bundle2); 
      /* create button */ 
    btn=(Button)findViewById(R.id.Button01); 
    btn.setOnClickListener(this); 
      /* delete button */ 
    btn2=(Button)findViewById(R.id.Button02); 
    btn2.setOnClickListener(this); 
} 

public void onClick(View view){ 
    if (view == btn) { 
     TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01); 
     TableRow tr = new TableRow(this); 

      /* get date */ 
     SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); 
     Date mydate = new Date(); 
     String dateString = dtformat.format(mydate); 
     TextView dt = new TextView(this); 
     dt.setText(dateString); 
     dt.setGravity(Gravity.CENTER_HORIZONTAL); 

      /* get time */ 
     SimpleDateFormat tmformat = new SimpleDateFormat("HH:mm", Locale.getDefault()); 
     Date mytime = new Date(); 
     String timeString = tmformat.format(mytime); 
     TextView tm = new TextView(this); 
     tm.setText(timeString); 
     tm.setGravity(Gravity.CENTER_HORIZONTAL); 

      /* drop-down list */ 

     String[] species = getResources().getStringArray(R.array.speciesList); 
     ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,species); 
     AutoCompleteTextView autoComplete = new AutoCompleteTextView(this); 
     autoComplete.setAdapter(adapter); 
     autoComplete.setThreshold(1); 
     autoComplete.setDropDownWidth(ViewGroup.LayoutParams.MATCH_PARENT); 
     autoComplete.setTextSize(10); 
     int options = autoComplete.getImeOptions(); 
     autoComplete.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE|EditorInfo.IME_FLAG_NO_FULLSCREEN); 

      /* GPS location */ 

     TextView latitudeTv = new TextView(this); 
     TextView longitudeTv = new TextView(this); 

     // create class object 
     myLocation = new MyLocation(tablelayout.this); 

     // check if GPS enabled 
     if (myLocation.canGetLocation()) { 

      Double latitude =myLocation.getLatitude(); 
      Double longitude =myLocation.getLongitude(); 

      latitudeTv.setText(latitude.toString()); 
      longitudeTv.setText(longitude.toString()); 
     } else { 
      // can't get location 
      // GPS or Network is not enabled 
      // Ask user to enable GPS/network in settings 
      myLocation.showSettingsAlert(); 
     } 

      /* user input */ 
     EditText et3 = new EditText(this); 
     et3.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE); 
     et3.setInputType(InputType.TYPE_CLASS_NUMBER); 
     EditText et4 = new EditText(this); 
     et4.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE); 

     tr.addView(dt); 
     tr.addView(tm); 
     tr.addView(autoComplete); 
     tr.addView(latitudeTv); 
     tr.addView(longitudeTv); 
     tr.addView(et3); 
     tr.addView(et4); 
     tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT)); 
    } 
    if (view == btn2) { 
     TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01); 
     int rowNumber = tl.getChildCount(); 
     tl.removeViews(rowNumber-1,1); 
    } 
    } 

} 

AndroidManifest.java

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

http://stackoverflow.com/a/23823363/6616489を参照してください。 'location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);'を使用したようです。 location.getLatitude()/ .getLongitude();を使用する前に –

+0

'getLastKnownLocation()'は日常的に 'null'を返します。楽観的に使用しますが、追加の手順(例: 'requestLocationUpdates()')を呼び出して位置データを取得する準備ができています。これは 'LocationManager'をカバーする適切なAndroidブックやトレーニングコースでカバーされています。 – CommonsWare

答えて

0

この問題は怠惰なgpsセンサーと遅延に関連しています。あなたのニーズに合わせて2つのソリューションベースを用意しています。

1 myLocationクラスをあなたのonclicklistener(oncreateなど)の外側に開始してインスタンス化します。あなたのボタンをクリックすると、あなたの携帯電話のセンサーは衛星と同期するための時間があります。

2 myLocationをアクティビティの外(その前)で起動し、myLocationをonLocationChangedメソッドで起動し、locationパラメータを別のクラスのstatic var(たとえば、sharingGps)に送信します。すべてのアクティビティやクラスからあなたの場所を共有することができます。

関連する問題