Monday 20 July 2015

WiFi state change Listener (Receiver) Android

There is no listener like OnClick listener to listen to WiFi status/state change during an activity.

To Listen to WiFi state change we have a to register a receiver that receives WiFi state change.

The following code helps you to listen to WiFi status change while running app in foreground

1.Add these permissions  to your Manifest file.


These are normal (PROTECTION_NORMAL) permissions. So you don't need check at runtime.

2. Create a receiver that has to run on receiving WiFi state change


3. create a boolean that check the registration of receiver.

This is required to avoid registering or deregistering the receiver multiple times.

4. Register your receiver in onResume method of the activity.

5. UnRegister the receiver when ever you pause the activity to avoid leak of receiver.

Wednesday 8 July 2015

How to start/ launch application at boot time Android

If you want your app to start-up automatically when Android boots up you need to the following
  
Step 1:
 add the permission android.permission.RECEIVE_BOOT_COMPLETED  to your Manifest file.
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Step 2: register receiver in your application in manifest.

        <receiver
          android:name=".YourReceiverName" <!-- name of your class that extends BroadcastReceiver -->
          android:enabled="true"          android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
          <intent-filter>
              <action android:name="android.intent.action.BOOT_COMPLETED" />
             <action android:name="android.intent.action.QUICKBOOT_POWERON" />
              <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
     </receiver>

     Note: this code should be inside of <application  ...> </application> of manifest file

Step 3: Create the class that extends BroadcastReceiver

public class YourReceiverName extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Your code that has to run on start up/ boot time
    }