-2

In my application i want to be notified in MainActivity when the Network status changes. This means, i want my app to know when there is no wifi connection and when there is wifi connection.

This code is easy. I have a doubt regarding BroadcastReceiver. I have created a class that extends BroadcastReceiver. This class can successfully see when there is wifi and when there is not.

My question is, how can i pass this information to the MainActivity so that my app can automatically send its recordings when Wi-Fi is detected?

Thanks

  • See my answer here to understand the BroadcastReceiver mechanisms : http://stackoverflow.com/a/36665760/4706693 – NSimon May 16 '16 at 14:51
  • My class that extends BroadcastReceiver already has a onReceive because it acts like a "trigger" when the wifi changes. What i want is to send a broadcast from that onReceive. I dont want to create a BroadcastReceiver in my MainActivity – Pedro Matos May 16 '16 at 21:36
  • Then an easier approach is to declare your receiver in your manifest. See these answers : http://stackoverflow.com/a/3767766/4706693 and http://stackoverflow.com/a/8780423/4706693 – NSimon May 17 '16 at 08:22
  • Thats what I have :) What i need now is that class that extends the BroadcastReceiver to send some signal to the MainActivity – Pedro Matos May 17 '16 at 13:31
  • So you want to have a broadcast receiver that catches the network changes, in order to send another broadcast to your mainActivity? Why not having your MainActivity to subscribe directly to the network changes? – NSimon May 17 '16 at 15:33
  • MainActivity has too much code already. I want to distribute it. Btw, i have done it, so i will post it as a response. – Pedro Matos May 18 '16 at 14:54

1 Answers1

0

I didn't want to create a BroadcastReceiver in my MainActivity, so I have create a BroadcastReceiver and an Intent Service where i do what I want.

BroadcastReceiver:

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

    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getActiveNetworkInfo();
    try{
        wifi = mWifi.isConnected();
    }
    catch(Exception e){
        Log.d("WifiReceiver", "wifiteste -> No connection");
    }

    if (wifi) {
        Log.d("WifiReceiver", "wifiteste - Wifi Connected");
        Intent background = new Intent(context, BackService.class);
        background.putExtra("wifi",true);
        context.startService(background);
    }
}

IntentService:

@Override
protected void onHandleIntent(Intent intent) {

    Bundle b = new Bundle();
    b = intent.getExtras();
    boolean status = b.getBoolean("wifi");
    if (!status){
        Log.d("BackS", "TESTE ->" + "no wifi");

    }
    else {
        Log.d("BackS", "wifiteste - wifi available information received");
        // Do what you want
    }
}