OnReceive никогда не вызывается после регистрации приемника BroadCast MainActivity из другого класса - PullRequest
0 голосов
/ 25 сентября 2018

ПРОБЛЕМА: Я пытаюсь зарегистрировать BroadcastReceiver для моего MapsActivity из метода (scanWifiSignal()) объекта (m) экземпляра другого класса (wifiConnectivity)), который создается в методе класса LocationUpdate (checkLocationSettings).Проблема в том, что OnReceive callback никогда не вызывается.если я перенесу код объявлений BroadcastReceiver и callback OnReceive в класс активности maps, то все будет работать нормально.Ниже упрощенный код.

ВОПРОС: Я прошу вас помочь мне определить проблему в приведенном ниже коде.Я думаю, что-то связано со сферой действия wifiScanReceiver, но я не уверен.Спасибо за вашу помощь.

MapsActivity

 public class  extends AppCompatActivity implements OnMapReadyCallback {

    public BroadcastReceiver wifiScanReceiver;
    private WifiManager wifiManager;
    private final LocationUpdate locationUpdate= new LocationUpdate(MapsActivity.this);



 @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        // If location permission is granted initialize Map
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            mapSync();

        } else {    

                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);    
        }    
    }

 @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;    

        // Check if localization permission is granted
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            mMap.setMyLocationEnabled(true);                

            // If wifi is the active connection, enable settings to get location updates and start wifi signal scan
            if(wifi.checkWifiConnection()){

                // Check if location settings are appropriated for the location request
                locationUpdate.checkLocationSettings(mLocationRequest,REQUEST_CHECK_SETTINGS, mFusedLocationClient,mLocationCallback,mMap);  


            } else {

                // Check if location settings are appropriated for the location request
                locationUpdate.checkLocationSettings(mLocationRequest,REQUEST_CHECK_SETTINGS,mFusedLocationClient,mLocationCallback,mMap);
                //Toast.makeText(getApplicationContext(),"no wifi, check tipo connessione attuale", Toast.LENGTH_LONG).show();

            }


        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
            }
        }
    }

wifiConnectivity

 public class wifiConnectivity {

        private MapsActivity mapsActivity;
        private BroadcastReceiver wifiScanReceiver;                
        private Context context;

        public wifiConnectivity(MapsActivity mapsActivity)
        {
              this.mapsActivity = mapsActivity;
                    this.context = mapsActivity.getApplicationContext();
                }


       public void scanWifiSignal(){

              final WifiManager wifiManager;            
              wifiManager = mapsActivity.getWifiManager();            
              wifiScanReceiver = new BroadcastReceiver() {

              @Override
              public void onReceive(Context context, Intent intent) {

                     mapsActivity.setLocalMaxSignalStrength(0);            
                    ist<ScanResult> results = wifiManager.getScanResults();

                            //public void handleWifiScanResults()
                            for (int i = 0; i < results.size(); i++) {

                                ScanResult el = results.get(i);

                                // Get signal level as a number from 0 to n-1
                                int signalLevel = wifiManager.calculateSignalLevel(el.level, 5);

                                // If signal level value is greater than the registered max, update the max value.
                                if (signalLevel >= mapsActivity.getLocalMaxSignalStrength()){
                                    mapsActivity.setLocalMaxSignalStrength(signalLevel);
                                }

                                Toast.makeText(mapsActivity.getApplicationContext(), "SSID:" + el.SSID + "frequency" + el.frequency + "lev:" + signalLevel, Toast.LENGTH_SHORT).show();
                            }

                        }
                    };
                    mapsActivity.setWifiScanReceiver(wifiScanReceiver);
                   this.context.registerReceiver(wifiScanReceiver, new IntentFilter(wifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

                   mapsActivity.setReceivingWifiScanResults(true);

                }

LocationUpdate

   public class LocationUpdate {
        private MapsActivity mapsActivity;
        private wifiConnectivity m ;




     public LocationUpdate(MapsActivity mapsActivity)
     {
            this.mapsActivity=mapsActivity;
     }
             public void checkLocationSettings(final LocationRequest mLocationRequest, final int REQUEST_CHECK_SETTINGS,  final FusedLocationProviderClient mFusedLocationClient, final LocationCallback mLocationCallback, final GoogleMap mMap) {


                // Get and check location services settings
                LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                        .addLocationRequest(mLocationRequest)
                        .setAlwaysShow(true);


                SettingsClient client = LocationServices.getSettingsClient(mapsActivity);
                Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

                task.addOnSuccessListener(mapsActivity, new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {

                        // All location settings are satisfied. The client can initialize
                        // location requests here
                        LocationUpdate locationUpdate = new LocationUpdate(mapsActivity);

                        locationUpdate.getLastKnownLocation(mFusedLocationClient);
                        locationUpdate.startLocationUpdates(mFusedLocationClient, mLocationCallback, mLocationRequest);

                        m=new wifiConnectivity(mapsActivity);
                        m.scanWifiSignal();


                    }
                });
                                    this.context = mapsActivity.getApplicationContext();
                        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...