如何在没有互联网连接的情况下阻止应用程序运行

时间:2016-11-06 10:34:45

标签: android login android-permissions

我正在尝试创建一个登录注册应用程序。显然我的应用程序需要互联网连接才能启动。我跟随其他用户的答案有同样的问题,但即使没有互联网连接我的应用程序仍然启动。提前谢谢。

这是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.claude.pickupcartbeta">

    <uses-sdk
        android:maxSdkVersion="24"
        android:minSdkVersion="16" />

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />

    <uses-permission android:name="android.permission.INTERNET" ></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>



    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".LogInActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainScreen"
            android:screenOrientation="landscape" />
        <activity android:name=".Register"
                  android:screenOrientation="portrait"></activity>
    </application>

</manifest>

活动在这里:

public class LogInActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCR‌​EEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_log_in);
    }

    public void MScreen(View view) {
        Intent intent = new Intent(this, MainScreen.class);
        startActivity(intent);
    }
}

1 个答案:

答案 0 :(得分:0)

在您的活动的onCreate功能中添加以下内容;

ConnectivityManager cm = (Connectivity Manager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&  activeNetwork.isConnectedOrConnecting();
if (!isConnected)
{
    // Toast... (Show some notification.
    finish();
}