检查android设备是否连接到网络

时间:2017-04-20 00:32:53

标签: java android

我需要知道如何检查设备是否连接到网络。

  1. 如果已连接,用户应该可以登录。
  2. 如果没有,用户应收到一条错误消息,告知:
  3.   

    在登录之前首先连接到网络...

    以下是我的代码:

    login.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
    
                    username = user.getText().toString();
                    password = pass.getText().toString();
                    DatabaseOperations dop = new DatabaseOperations(ctx);
                    Cursor cr = dop.getInformation(dop);
                    cr.moveToFirst();
                    boolean loginstatus=false;
                    String Name= "";
                    do
                    {
                        if(username.equals(cr.getString(2))&& (password.equals(cr.getString(3))))
                        {
                            loginstatus=true;
                            Name = cr.getString(0);
                        }
    
    
                    }while(cr.moveToNext());
                    if(loginstatus)
                    {
                        Toast.makeText(ctx, "Welcome \n" + Name, Toast.LENGTH_LONG).show();
                        Intent i = new Intent(ctx, MainActivity.class);
                        startActivity(i);
                        finish();
                    }else
                    {
                        Toast.makeText(ctx, "Check your Credentials..", Toast.LENGTH_LONG).show();
                    }
                    }
    
            });
    

2 个答案:

答案 0 :(得分:1)

创建广播接收器以从操作系统接收网络事件:

public class ConnectivityReceiver extends BroadcastReceiver {
    private boolean isConnected = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            isConnected = activeNetwork != null &&
                    activeNetwork.isAvailable();

            if (isConnected) {
                onConnectionRestored();
            } else {
                onConnectionInterrupted();
            }
        }
    }

    private void onConnectionRestored() { //implement me }
    private void onConnectionInterrupted() { //implement me }

}

然后在您的activity / fragment / presenter的onStart()方法上注册它以开始收听:

connectivityReceiver = new ConnectivityReceiver();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityReceiver, intentFilter);

完成后不要忘记取消注册:

@Override
protected void onStop() {
    unregisterReceiver(connectivityReceiver);
    super.onStop();
}

答案 1 :(得分:0)

您可以使用broadcastreceiver检查互联网是否连接如下。

MainActivity.Java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static TextView internetStatus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        internetStatus = (TextView) findViewById(R.id.internet_status);

        // At activity startup we manually check the internet status and change
        // the text status
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            changeTextStatus(true);
        } else {
            changeTextStatus(false);
        }
    }
    // Method to change the text status
    public void changeTextStatus(boolean isConnected) {

        // Change status according to boolean value
        if (isConnected) {
            internetStatus.setText("Internet Connected.");
            internetStatus.setTextColor(Color.parseColor("#00ff00"));
        } else {
            internetStatus.setText("Internet Disconnected.");
            internetStatus.setTextColor(Color.parseColor("#ff0000"));
        }
    }

    @Override
    protected void onPause() {

        super.onPause();
        MyApplication.activityPaused();// On Pause notify the Application
    }

    @Override
    protected void onResume() {

        super.onResume();
        MyApplication.activityResumed();// On Resume notify the Application
    }
}

Receiver.Java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Created by root on 7/4/17.
 */
public class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {

            boolean isVisible = MyApplication.isActivityVisible();// Check if
            // activity
            // is
            // visible
            // or not
            Log.i("ActivityVisible ", "visible : " + isVisible);

            // If it is visible then trigger the task else do nothing
            if (isVisible == true) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager
                        .getActiveNetworkInfo();

                // Check internet connection and accrding to state change the
                // text of activity by calling method
                if (networkInfo != null && networkInfo.isConnected()) {

                    new MainActivity().changeTextStatus(true);
                    Log.i("ActivityVisible ", "visible : " + isVisible);
                } else {
                    new MainActivity().changeTextStatus(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

MyApplication.Java

public class MyApplication  extends Application {
    // Gloabl declaration of variable to use in whole app

    public static boolean activityVisible; // Variable that will check the
    // current activity state

    public static boolean isActivityVisible() {
        return activityVisible; // return true or false
    }

    public static void activityResumed() {
        activityVisible = true;// this will set true when activity resumed

    }

    public static void activityPaused() {
        activityVisible = false;// this will set false when activity paused

    }

}

Manifest.Java

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theme.broadcastreceiver">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- This permissions are neccessary for broadcast receiver -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".Receiver"
            android:enabled="true" >
            <intent-filter>

                <!-- Intent filters for broadcast receiver -->
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                <action android:name="android.net.wifi.STATE_CHANGE" />
            </intent-filter>
        </receiver>
    </application>

</manifest>