2017-10-27 11 views
3

UPDATE 시작 : locationServiceMCV github repo브로드 캐스트 리시버 (1 십일, 2017) activity1에

위치가 검색 될 것 같다 : I 본원 연결된 MCV 예에서 오류를 재현 할 수 있었다 두 번째 활동으로 이동할 때만 따라서이 문제는 수명주기와 관련이 있다고 생각합니까?

서비스 I 성공적으로 위치를 가져옵니다 내 mainActivity에서 브로드 캐스트 리시버를 등록했습니다

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    Log.d("personal", "got into onConnected"); 

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (location == null) { 
     Log.d("personal", "location null"); 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } else { 
     Log.d("personal", "location not null"); 
     handleNewLocation(location); 
    } 
} 

private void handleNewLocation(Location location) { 
    Log.d("personal", "got to handleNewLocation"); 
    currentLatitude = location.getLatitude(); 
    currentLongitude = location.getLongitude(); 
    Log.d("personal", "lat from handleNewLocation is " + currentLatitude.toString()); 
    Log.d("personal", "long from handleNewLocation is " + currentLongitude.toString()); 
    if (currentLatitude != null && currentLongitude != null) { 
     setUpGeoFire(); 
     sendToActivity(currentLatitude, currentLongitude); 
    } 
} 

public void sendToActivity(Double currentLatitude, Double currentLongitude){ 
    Log.d("personal", "got to sendToActivity"); 
    Intent intent = new Intent("locationServiceUpdates"); 
    intent.putExtra("ServiceLatitudeUpdate", currentLatitude.toString()); 
    intent.putExtra("ServiceLongitudeUpdate", currentLongitude.toString()); 
    if(serviceContext != null){ 
     LocalBroadcastManager.getInstance(serviceContext).sendBroadcast(intent); 
     Log.d("personal", "broadcast launched from the location service"); 
     Toast.makeText(this, "broadcast launched from the location service", Toast.LENGTH_SHORT).show(); 
    } else{ 
     Log.d("personal", "didn't broadcast the location updates because serviceContext is null"); 
    } 
} 

:

나는 사용자의 위치를 ​​얻고 의도에 위도와 경도를 방송하는 서비스를 잘 정보 :

주요 활동

//Start location service// 
    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_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION); 
     return; 
    } 
    startLocationService(); 
    BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      // Get extra data included in the Intent 
      currenLatitude = Double.parseDouble(intent.getStringExtra("ServiceLatitudeUpdate")); 
      currentLongitude = Double.parseDouble(intent.getStringExtra("ServiceLongitudeUpdate")); 
      Log.d("personal", "onReceive of broadcast receiver reached"); 
      Log.d("personal", "onReceive lat is " + currenLatitude.toString()); 
      Log.d("personal", "onReceive long is " + currentLongitude.toString()); 
      ArrayList<String> children = new ArrayList<>(); 
      children.add(userId + "_current"); 
      setUpFirebaseAdapter(children); 
     } 
    }; 
    IntentFilter intentFilter = new IntentFilter("locationServiceUpdates"); 
    LocalBroadcastManager.getInstance(MainActivity.this).registerReceiver(mMessageReceiver, intentFilter); 
,

위치 방송을 수신해야하는 또 다른 활동 인 NewSwarmReportActivity가 있습니다. 나는 앱이 종료됩니다 심지어 배경에 적극적으로 서비스를 유지하기 바라고, 그래서 이것은가 매니페스트에 모습입니다 :

매니페스트 :

<service 
     android:name=".services.LocationService" 
     android:enabled="true" 
     android:exported="true"> 
</service> 

난 확실하지 내가 여부 두 번째 활동에서 위치 서비스를 다시 시작해야합니다 (의도적으로 첫 번째 활동에서 서비스를 종료 할 코드가 없기 때문에 추측하고 있습니다). 그러나 NewSwarmReportActivity에서 브로드 캐스트 리시버를 등록하거나 방법은, 작동하지 않는 것 :

NewSwarmReportActivity :

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

    ButterKnife.bind(this); 
    ... 

    getSharedPreferences(); 
    Log.d("personal", "newSwarm userName is " + userName); 
    Log.d("personal", "newSwarm userId is " + userId); 

    startLocationService(); //Don't think I should do this. 
    IntentFilter intentFilter = new IntentFilter("locationServiceUpdates"); 

    BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      // Get extra data included in the Intent 
      currenLatitude = Double.parseDouble(intent.getStringExtra("ServiceLatitudeUpdate")); 
      currentLongitude = Double.parseDouble(intent.getStringExtra("ServiceLongitudeUpdate")); 
      Log.d("personal", "onReceive in NewSwarmReportActivity of broadcast receiver reached"); 
      Log.d("personal", "onReceive in NewSwarmReportActivity lat is " + currenLatitude.toString()); 
      Log.d("personal", "onReceive in NewSwarmReportActivity long is " + currentLongitude.toString()); 
      if (userId != null && userName != null && currenLatitude != 0.0 && currentLongitude != 0.0) { 
       progressBar.setVisibility(View.GONE); 
       reportSwarmButton.setVisibility(View.VISIBLE); 
       addImageButton.setVisibility(View.VISIBLE); 
      } else { 
       Log.d("newSwarm", "either location or user info is null!"); 
      } 
     } 
    }; 
    LocalBroadcastManager.getInstance(NewSwarmReportActivity.this).registerReceiver(mMessageReceiver, intentFilter); 

} 

난 당신이 내 새로움을 용서 바랍니다. onReceive은 NewSwarmReportActivity에서 결코 호출되지 않는 것 같습니다. 나는 이유를 알 수 없다. 어떤 도움이라도 대단히 감사합니다. 여기

내 모듈의 Gradle을 파일입니다 :

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 26 
    defaultConfig { 
     applicationId "fisherdynamic.locationservicemcv" 
     minSdkVersion 15 
     targetSdkVersion 26 
     versionCode 1 
     versionName "1.0" 
     testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
} 
buildTypes { 
    release { 
     minifyEnabled false 
     proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
    } 
} 
} 

dependencies { 
    implementation fileTree(dir: 'libs', include: ['*.jar']) 
    implementation 'com.android.support:appcompat-v7:26.1.0' 
    implementation 'com.android.support.constraint:constraint-layout:1.0.2' 
    testImplementation 'junit:junit:4.12' 
    androidTestImplementation 'com.android.support.test:runner:1.0.1' 
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' 
    compile 'com.google.android.gms:play-services-location:10.0.1' 
} 
+0

언제 수신자를 등록 취소합니까? 활동의 라이프 사이클에서 특정 전이 동안 등록 해제가 권장됩니다. [이 문서] (https://developer.android.com/guide/components/broadcasts.html#context-registered_receivers)를 참조하십시오. 귀하의 활동이 일시 중지/중단/폐기되었으며 수신자가 등록 취소되었거나 문맥이 더 이상 유효하지 않은 것일 수 있습니까? – Cheticamp

+0

@Cheticamp, mMessageReceiver는 주 활동에 등록되지만 결코 등록이 해제되지 않습니다. 나는 처음에 이것을 목적으로했다. 수신기가 누출되고 있다고 가정할까요? 그게 문제의 일부입니까? 누수가 두 번째 활동에서 방송 수신기의 새로운 선언을 방해 할 수 있다는 것이 합리적입니까? – Atticus29

+1

누출을 피하기 위해 주 활동의'onDestroy()'에서 수신기를 등록 해제해야합니다. 그러나 이것이 당신 문제라고 생각하지 않습니다. 나는 당신이 당신의 떼 짓기 활동이 방송을 기대하기 전에'onCreate()'를 실행하고 있다고 가정합니다. [MCVE] (https://stackoverflow.com/help/mcve)는 커뮤니티의 답변에 따라 속도가 빨라집니다. – Cheticamp

답변

-1

활동의 형태로 서비스에 브로드 캐스트를 보낼 수있는이 코드를 사용해보십시오, 여기 내 활동에

 Intent intent = new Intent(getPackageName()); 
     intent.putExtra(LOCATION_UPDATED, location); 
     sendBroadcast(intent); 

방송을 수신하는 코드입니다,

private BroadcastReceiver broadcastReceiver; 

수신자 등록,

broadcastReceiver = createBroadcastReceiver(); 
registerReceiver(broadcastReceiver, new IntentFilter(getPackageName())); 


private BroadcastReceiver createBroadcastReceiver() { 
     return new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 

       if (intent.hasExtra(LocationService.LOCATION_UPDATED)) { 
        //Log.e(TAG, "##--Location Updated--##"); 
        Bundle b = intent.getExtras(); 
        if (b != null) { 
         mCurrentLocation = (Location) b.get(LocationService.LOCATION_UPDATED); 
        } 
       } 

     } 
    }; 
}