Search code examples
androidandroid-intentbroadcastreceiverwifi

open app when connect with wifi


How can I open my application when an user enters a zone that has wi-fi? Is this possible? Suppose my application is onPause() state (means My Device's homescreen). now when device connected with wifi. it will automatically open my application.


Solution

  • Try add broadcast receiver and listen network changes, when wi-fi connected start your activity. Something like this solution

    public class ConnectivityReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
                    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                    if (((null != wifi)&&(wifi.isAvailable())) || ((null != mobile)&&(mobile.isAvailable()))){
                        Intent uplIntent = new Intent(context, YourActivity.class);
                        uplIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(uplIntent);
                    }
    
        }
    }
    

    And add to manifest

        <receiver android:name=".receiver.ConnectivityReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>