activity2中的BroadcastReceiver未接收在activity1中启动的服务发送的广播

时间:2017-10-27 18:57:37

标签: android service broadcastreceiver android-broadcast

更新(2017年11月1日):我能够在此处链接的MCV示例中重现错误: locationServiceMCV github repo

似乎只有在我第二次导航到活动时才会检索位置。所以,我猜这个问题与生命周期有关?

我有一项获取用户位置的服务,并在意图中广播纬度和经度:

服务

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

我不确定是否必须在第二个活动中再次启动位置服务(我猜/不希望,特别是因为我没有代码在我的第一个活动中故意关闭服务)。但无论哪种方式,在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);

}

我希望你能原谅我的新意。似乎永远不会在NewSwarmReportActivity中调用onReceive。我不清楚为什么不。非常感谢任何帮助。

这是我模块的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'
}

1 个答案:

答案 0 :(得分:-1)

尝试使用此代码将广播发送到活动表单服务

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

在我的活动中,这里是代码接收广播,

private BroadcastReceiver broadcastReceiver;

注册Receiver,

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

        }
     };
}