Android端末OS4.4から使えたGPSコード(java用)
◎AndroidManifest.xml に追加
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
とフォアグラウンド指定
<application~
~</activity>
<!-- Foreground services in Q+ require type. -->
<service
android:name=".MainActivity"
android:enabled="true"
android:exported="true"
android:foregroundServiceType="location" />
◎モジュールの build.gradle に追加
implementation 'com.google.android.gms:play-services-location:17.0.0'
その後 SYNCを実行
◎MainActivity.java は要求に応じてimport「Alt+Enter」を実行。以前と違うのは「implements LocationListener」関連が無い事。
public class MainActivity extends AppCompatActivity {
// GPS用の変数
private FusedLocationProviderClient fusedLocationClient;
//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// GPS用の変数
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// 1回目のrequestLocationUpdates呼出
startLocationRequest();
}
// 2回以上呼び出されるので関数にする
private void startLocationRequest() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 位置情報パーミッション呼出→戻りに行く
String [ ] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(this,permissions,1000);
return;
}
// 位置情報の取得方法を設定
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(15000); // 位置情報更新間隔の希望(msec) 15秒
locationRequest.setFastestInterval(5000); // 位置情報更新間隔の最速値(msec) 5秒
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); // この位置情報要求の優先度
fusedLocationClient.requestLocationUpdates(locationRequest, new MyLocationCallback(), null);
}
// 位置情報受取コールバッククラス
private class MyLocationCallback extends LocationCallback {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
// 現在値を取得
Location location = locationResult.getLastLocation();
Date ima = new Date(location.getTime());
String buf = String.format(Locale.US,"%tH%tM%tS",ima,ima,ima)+">"+String.valueOf(location.getLatitude())+","+String.valueOf(location.getLongitude());
Log.d("kyo",buf);
dispmesse(buf);
};
}
// パーミッション呼出からの戻り
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions, @NonNull int grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// パーミッション後の必要な処理
Log.d("GPS", "set");
// 2回目以降のrequestLocationUpdates呼出
startLocationRequest();
} else {
// パーミッションが得られなかった時
// 処理を中断する・エラーメッセージを出す・アプリケーションを終了する等
Log.d("GPS", "no");
finish();
}
break;
}
}
// トースト用関数
private void dispmesse(String str) {
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
}
}
※自分メモ
※参考ブログ