0

I'm developing an app that needs to listen for wifi changes. When the users device detects a certain wifi ssid I need to have a notification appear on the device. The notification will allow the users to perform an action if desired.

I have found this information which is similar Android WIFI How To Detect When Specific WIFI Connection is Available

What I really want to know is, where in the application do I listen for the Wifi changes? Where does the code to listen go and how do I allow the app to listen for this efficiently in the background.

I would really appreciate any help, Thanks

Community
  • 1
  • 1
  • 2
    the link you found seem to have what you need. – muratgu Apr 29 '16 at 22:41
  • Just look at the code in that post. Anywhere you have a Context (like an Activity), you can replace `context` with `getApplicationContext().registerReceiver` – OneCricketeer Apr 29 '16 at 22:43
  • I think the post I linked does have a lot of what I'm looking for but the confusing part is where to place the listener code so it's running in the background. Nerevar seems to have given a good answer below that I will check out tomorrow. Thanks – Eoghan Mc Apr 29 '16 at 23:19

1 Answers1

0

When you want to run a task like this in the background even when your application isn't actively running you should use a Service (https://developer.android.com/reference/android/app/Service.html).

If this is supposed to run all the time from that the user installs the application you can listen for the boot broadcast and start the service. I'm not sure if this broadcast gets notified if you register once the device has been booted. You can solve this by starting the service once you start the Activity.

To make sure the Service keeps running in the background you need to return START_STICKY in the onStartCommand. (see the snippet below). But note that the service will run until you either stop it or your application is uninstalled when you do this.

Here's a snippet that should help you get started in combination with the link you already found.

public class WifiListener extends Service {

@Override
public void onCreate() {
    super.onCreate();

     // Register broadcast receiver here
}

@Override
public void onDestroy() {
    super.onDestroy();

    // Stop listening to broadcast receiver here
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

}