2017-10-27 26 views
3

UPDATE(2017年11月1日)activity1に開始しました:私は、ここにリンクされMCVの例では、エラーを再現することができた: locationServiceMCV github repoBroadcastReceiver受信していないが、

場所が検索されたようです2回目のアクティビティに移動したときに限ります。だから、問題はライフサイクルと関係があると思っていますか?

私は、ユーザの位置を取得し、意思で緯度と経度を放送するサービスがあります。

サービス

@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"); 
    } 
} 

を私が場所を取得し、私のmainActivityでBroadcastReceiverを、正常に登録されましたうまく情報:

主な活動

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

私はわからない私はどうか2回目のアクティビティで再度位置情報サービスを開始する必要があります(特に私の最初のアクティビティで目的のサービスを停止するコードがないので、私は推測/希望していません)。しかしNewSwarmReportActivityでBroadcastReceiverを登録するいずれかの方法では、動作していないようです:

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はメインアクティビティに登録されますが、登録解除されることはありません。私は当初これを目的にしました。受信機が漏れていると思われますか?それは問題の一部ですか?漏れが第2の活動で放送受信機の新しい宣言を妨害することは意味をなさないでしょうか? – Atticus29

+1

メインのアクティビティの 'onDestroy()'で受信機を登録解除して、漏れを防ぐ必要がありますが、それはあなたの問題ではないと思います。私は、放送を期待する前にあなたのswarmアクティビティが '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); 
        } 
       } 

     } 
    }; 
} 
関連する問題