0
위치를 얻는 서비스가 있습니다.이 서비스는 API < 23에서 작동하지만 API> 23에서는 네트워크가있는 위치를 얻지 못합니다. GPS를 사용하여 위치 정보를 얻습니다.왜 API> 23에서 FusedLocationApi (onLocationChanged)가 호출되지 않습니까?
public class TrackLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final long SYNCHRONIZATION_INTERVAL = 60 * 60 * 1000;
private static boolean isServiceRunning;
private static final String TAG = "SADASDQWREQWRwerwer";
private int notificationId = 9999;
private GoogleApiClient googleApiClient;
private TrackLocationApplication app;
private DataHelper dataHelper;
public static boolean isServiceRunning() {
return isServiceRunning;
}
private static void setIsServiceRunning(boolean isServiceRunning) {
TrackLocationService.isServiceRunning = isServiceRunning;
EventBus.getDefault().post(AppEvent.SERVICE_STATE_CHANGED);
}
public TrackLocationService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
app = (TrackLocationApplication) getApplication();
dataHelper = DataHelper.getInstance(getApplicationContext());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
createGoogleApiClient();
connectGoogleApiClient();
TrackLocationService.setIsServiceRunning(true);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
stopLocationUpdates();
cancelNotification();
app.setStartLocation(null);
TrackLocationService.setIsServiceRunning(false);
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged");
if (app.getStartLocation() == null) {
app.setStartLocation(location);
}
Log.i("ASDASDASDASDA", location.getLatitude() + "" + location.getLongitude());
updateLocationData(location);
}
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended");
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d(TAG, "onTaskRemoved");
}
private void createGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void connectGoogleApiClient() {
if (googleApiClient != null) {
if (!(googleApiClient.isConnected() || googleApiClient.isConnecting())) {
googleApiClient.connect();
} else {
Log.d(TAG, "Client is connected");
startLocationUpdates();
}
} else {
Log.d(TAG, "Client is null");
}
}
private void startLocationUpdates() {
Log.i("ASDASDASDASDA", "1");
LocationRequest locationRequest = app.createLocationRequest();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
scheduleDataSynchronization();
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
stopDataSynchronization();
}
private void scheduleDataSynchronization() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TrackLocationSyncReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
SYNCHRONIZATION_INTERVAL, alarmIntent);
}
private void stopDataSynchronization() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TrackLocationSyncReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.cancel(alarmIntent);
}
private void updateLocationData(Location location) {
Location startLocation = app.getStartLocation();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float distance = Utils.distFromCoordinates((float) startLocation.getLatitude(),
(float) startLocation.getLongitude(),
(float) latitude,
(float) longitude);
String timeText = Utils.formatTime(System.currentTimeMillis());
long date = System.currentTimeMillis();
dataHelper.saveLocation(LocationData.getInstance(latitude, longitude, "2"));
updateNotification(timeText);
}
private void updateNotification(String text) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.qomGardy))
.setContentText(text);
Intent resultIntent = new Intent(this, GetNumberActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(GetNumberActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
mNotificationManager.notify(notificationId, notification);
}
private void cancelNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(notificationId);
}
private void synchronizeData() {
new AsyncTask<Void, Void, TrackLocationResponse>() {
private List<LocationData> locations;
@Override
protected TrackLocationResponse doInBackground(Void[] params) {
TrackLocationResponse response = null;
//locations = dataHelper.getLocationsToSync();
if (locations != null && locations.size() > 0) {
String deviceId = TrackLocationPreferencesManager.getDeviceId(getApplicationContext());
String userName = TrackLocationPreferencesManager.getUserName(getApplicationContext());
TrackLocationRequest request = TrackLocationRequest.getInstance(locations, deviceId, userName);
ITrackLocationClient client = new TrackLocationClient();
response = client.addTrack(request);
if (response != null && response.getStatus() == TrackLocationResponse.RESPONSE_CODE_OK) {
Log.d("TrackLocationSync", "Synced " + locations.size() + " items");
//dataHelper.markLocationsSynced(locations);
}
} else {
Log.d("TrackLocationSync", "No data to be synced");
}
return response;
}
@Override
protected void onPostExecute(TrackLocationResponse response) {
super.onPostExecute(response);
if (response != null && response.getStatus() == TrackLocationResponse.RESPONSE_CODE_OK) {
String message = null;
List<FriendResult> results = response.getResult();
if (results != null && results.size() > 0) {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("Hi from ");
for (FriendResult r : results) {
messageBuilder.append(" ");
messageBuilder.append(r.getTitle());
messageBuilder.append(",");
}
messageBuilder.deleteCharAt(messageBuilder.length() - 1);
message = messageBuilder.toString();
} else {
message = "Sync " + locations.size() + " items at " + Utils.formatTime(System.currentTimeMillis());
}
updateNotification(message);
}
}
}.execute();
}
}
나는 API> (23) 내 매니페스트에 이러한 권한을 추가 :
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" />
이 onLocationChanged()
라고하지 않습니다!
제 활동에서 나는 모든 허가를 얻습니다.
당신이하지 매니페스트에, 런타임에 요청 권한이 필요 23+ API에
있습니다. –
@JoJoRoid 수정 확인 – X3Btel