2016-08-05 20 views
0

これまでのところです。現在の位置を緯度と経度として2つの別々のテキストビューに表示することになっています。電話機の現在地を取得していませんか? [Android]

私はエミュレータと実際のアンドロイド携帯電話でこれを試してみましたが、どちらでも動作しません。何も起こらず、textviews doestは任意の座標を表示します。エラーもありません。

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

private static final int LOCATION_REQUEST_INTERVAL = 60000; 
private static final int LOCATION_REQUEST_FASTEST = 15000; 
private static final int MY_PERMISSION_REQUEST_READ_COARSE_LOCATION = 102; 
private TextView latitudeTextView; 
private TextView longitudeTextView; 
private ImageButton imageButton; 
private GoogleApiClient googleApiClient; 
private LocationRequest locationRequest; 
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi; 
private double mLatitude; 
private double mLongitude; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    latitudeTextView = (TextView) findViewById(R.id.latitudeTextView); 
    longitudeTextView = (TextView) findViewById(R.id.longitudeTextView); 
    imageButton = (ImageButton) findViewById(R.id.imageButton); 

    googleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this).build(); 

    locationRequest = new LocationRequest(); 
    locationRequest.setInterval(LOCATION_REQUEST_INTERVAL); 
    locationRequest.setFastestInterval(LOCATION_REQUEST_FASTEST); 
    locationRequest.setPriority(locationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    requestLocationUpdates(); 
} 

private void requestLocationUpdates() { 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     ActivityCompat.requestPermissions(this, 
       new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, 
       MY_PERMISSION_REQUEST_READ_COARSE_LOCATION); 

     return; 
    } 
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

@Override 
public void onLocationChanged(Location location) { 
    mLatitude = location.getLatitude(); 
    mLongitude = location.getLongitude(); 
    latitudeTextView.setText(String.valueOf(mLatitude)); 
    longitudeTextView.setText(String.valueOf(mLongitude)); 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    googleApiClient.connect(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    googleApiClient.disconnect(); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    if(googleApiClient.isConnected()) 
     requestLocationUpdates();; 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this); 
} 

}

なぜそれが機能しないのですか?私はいくつかのガイドに従っています。そのうちの1つはアンドロイドの開発者ガイドです。

ご意見やご提案はありますか?

入力いただきありがとうございます。

+1

「Log.d」を使って、正しく動作しないコード行を特定する必要があります。予期しない、または価値が得られない点を見つけたら、質問を投稿してください。したがって、すべての行の後に 'Log.d'文を置いてください。正確に働いていないものが何であるかを把握せずに時間を無駄にすることを要請することはありません。 – suku

答えて

1

私の経験ではエミュレータはPRIORITY_BALANCED_POWER_ACCURACYでは動作しませんが、 PRIORITY_HIGH_ACCURACYが必要です。

変更コードの行

locationRequest.setPriority(locationRequest.PRIORITY_BALANCED_POWER_ACCURACY)。

LocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)に

また、アクセス許可の要求ダイアログボックスでは、粗い場所に対してのみ許可が与えられます。私はこれを素晴らしい場所に変更します。コードの行を変更:

新しいString [] {Manifest.permission.ACCESS_COARSE_LOCATION、Manifest.permission.ACCESS_FINE_LOCATION}、 MY_PERMISSION_REQUEST_READ_COARSE_LOCATION)。

requestPermissions(新しい 文字列[] {} Manifest.permission.ACCESS_FINE_LOCATION、 MY_PERMISSION_REQUEST_FINE_LOCATION)。

と最後MY_PERMISSION_REQUEST_FINE_LOCATION

の文字列値を定義し、位置権限デバイスまたはエミュレーターに付与されていることを確認してください。 [設定] - > [アプリ]に移動し、アプリが位置情報サービスを使用していることを確認します。そうでない場合は、「アクセス許可」をクリックしてサービスをオンにします。

+0

こんにちは、ようこそ。投稿するときは、コードを転記するときにコードフォーマットのマークダウンを使用してください - ガイドhttp://stackoverflow.com/editing-help#codeを参照してください。ハッピーハッキング! – theFunkyEngineer

3

クラスGpsTracker.javaを作成しますように今、あなたはGpsTracker.javaのインスタンスを作成する場所を取得することができます

import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.GpsStatus; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

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 = 1000; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 100000 * 60 * 1; // 5 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 
       //showSettingsAlert(); 

      } 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 
       else { 
        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(); 
      System.exit(0); 

      } 
     }); 

     // 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; 
    } 

} 

GPSTracker gpstracker=new GPSTracker(EditProfile.this); 
double lat=gpstracker.getLatitude(); 
double longitude=gpstracker.getLongitude(); 
関連する問題