简体   繁体   中英

Make an App need Internet Connection to play

I just want to ask how to make an app need Internet Connection to launch and if user smartphone don't have connection so the app will show some attention like Clash of Clans game or another online game

在此处输入图片说明

If connection was lost or turn off, the app will show some attention like that

Anyone can explain or give some reference to how to make like that?

Using BroadcastReceiver you can archive this.

public class InternetChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Open your alert dialog here.


        }
    }
}

In Manifest file register your BroadcastReceiver .

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.checkinternet"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".InternetChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />                
            </intent-filter>
        </receiver>
    </application>

</manifest>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM