Send information from a class to an activity

0

I have this class:

public class WifiReceiver extends BroadcastReceiver {

private static final String TAG = "WifiReceiver";

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

    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

    if (networkInfo != null && networkInfo.isConnected()) {
        WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
        String ssid = wifiInfo.getSSID();
        Toast.makeText(context, "Conectado a: " + ssid, Toast.LENGTH_SHORT).show();

        Log.i(TAG, "Connected to : " + ssid);
    }else{
        Log.e(TAG, "Network not connnected!");
    }
}
}

Now what I want is that when entering the if () it tells my activity to hide the progressBar and show a button. I do not know how to do it. This is the activity

public class HelperConnection extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_helper_connection);

    this.setTitle("Login UCF");

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    bindUI();

    Toast.makeText(this, "Siga los pasos para establecer conexión con la red", Toast.LENGTH_LONG)
            .show();

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (textInputUser.getText().length() == 0)
                textInputUser.setError("Campo requerido");
            else if (textInputPassw.getText().length() == 0)
                textInputPassw.setError("Campo requerido");

            else {
                mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.in_from_left));
                mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.out_from_left));

                mViewFlipper.showNext();

                getSupportActionBar().setDisplayHomeAsUpEnabled(false);

                progressBar.performClick();

                if (wifiManager.isWifiEnabled()) {
                    wifiManager.removeNetwork(wifiManager.getConnectionInfo().getNetworkId());
                    detectWifi();

                } else {
                    wifiManager.setWifiEnabled(true);
                    wifiManager.removeNetwork(wifiManager.getConnectionInfo().getNetworkId());
                    detectWifi();
                }
            }
        }
    });

    btnFinish.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(HelperConnection.this, LoginActivity.class);
            intent.putExtra("runWeb", true);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            finish();
            startActivity(intent);
        }
    });
}

private void bindUI() {
    mViewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
    mContext = this;
    btnFinish = (Button) findViewById(R.id.btnFinish);
    btnNext = (Button) findViewById(R.id.btnNext);
    progressBar = (ProgressBar) findViewById(R.id.load_steps_login);
    wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    textInputPassw = (TextInputEditText) findViewById(R.id.edit_text_passw);
    textInputUser = (TextInputEditText) findViewById(R.id.edit_text_user);
    loginActivity = new LoginActivity();
}

private void tryConnection() {
    loginActivity.helperConnect(wifiManager);
    Toast.makeText(this, "Espere...", Toast.LENGTH_SHORT).show();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    WifiReceiver wifiReceiver = new WifiReceiver();
    registerReceiver(wifiReceiver, intentFilter);
}

The detectWifi function is irrelevant. How can I tell this activity that when I connect to Wi-Fi do what I asked earlier? Thanks for the help

    
asked by Alex Rivas 23.05.2018 в 16:11
source

1 answer

2

The most immediate option that occurs to me is simply with an Intent, but it depends on how your app is made. You send another intent from the WifiReceiver to your Activity explicitly. To do this, make sure that you only have one instance of the Activity (otherwise another activity will be created). I refer specifically to the launchModes

link

If for whatever reason you can not / want to use intents, then you can use a pattern like the Observer: The objective is that your activity (or any other class) subscribes to WifiManager , and this one, to your Once, call (s) when you have new information:

1 - Create in your WifiReceiver class a method called for example: void subscribe(WifiChangeListener listener)  In this method, save a reference to the listener in, for example, a List . Make this list of subscribers a variable of the instance.

2 - Implement an interface called WifiChangeListener (or the name you want) with a method called (for example) void onWifiChange(String ssid);

3 - Make your Activity implement the interface 'WifiChangeListener, (and therefore the method onWifiChange (String ssid))

4 - Finally, in your Activity, in OnCreate , subscribe the class, the call will be something like that. It is important that you only create a WifiReceiver in the Activity, so save the reference in a variable of the instance. wifiReceiver = new WifiReceiver(); wifiReceiver.subscribe(this);

5 - When you receive the intent in WifiReceiver , simply go through the list of subscribers and for each of them call the void onWifiChange(String ssid) , if you want to pass info then modify the signature of the onWifiChange to what you need.

That is, something like this would be:

  public class WifiReceiver extends BroadcastReceiver {

        private static final String TAG = "WifiReceiver";
        private final List<WifiChangeListener> listeners = new ArrayList<>();

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

            NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

            if (networkInfo != null && networkInfo.isConnected()) {
                WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                String ssid = wifiInfo.getSSID();
                for(final WifiChangeListener listener : listeners) {
                    listener.onWifiChange(ssid);
                }

                Log.i(TAG, "Connected to : " + ssid);
            }else{
                Log.e(TAG, "Network not connnected!");
            }
        }

        public void subscribe(@NonNull final WifiChangeListener listener) {
            listeners.add(listener)
        }
    }

And your Activity:

public class HelperConnection extends AppCompatActivity {
final WifiReceiver wifiReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        wifiReceiver = new WifiReceiver() //solo lo instancias aquí y te lo guardas
        .....
 }
 ...

private void tryConnection() {
    loginActivity.helperConnect(wifiManager);
    Toast.makeText(this, "Espere...", Toast.LENGTH_SHORT).show();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    //no instanciamos de nuevo wifiReceiver, sino que usamos la misma instancia:
    //WifiReceiver wifiReceiver = new WifiReceiver(); --> BORRAR
    registerReceiver(wifiReceiver, intentFilter);
}
    
answered by 23.05.2018 / 17:02
source