проверка связи с приемником вещания - PullRequest
0 голосов
/ 01 ноября 2018

Я работаю в проекте, когда мне нужно проверить подключение к интернету и делать что-то в фоновом режиме, но это не работает. вот код

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            Toast.makeText(context, "Connectivity changed", Toast.LENGTH_SHORT).show();
        }
    }
}

Манифест:

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


        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

1 Ответ

0 голосов
/ 01 ноября 2018

Используйте это

ConnectivityReceiver.java

public class ConnectivityReceiver
    extends BroadcastReceiver {

public static ConnectivityReceiverListener connectivityReceiverListener;

public ConnectivityReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent arg1) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }
}

public static boolean isConnected() {
    ConnectivityManager
            cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}


public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}
}

MyApplication.java

public class MyApplication extends Application {

private static MyApplication mInstance;

@Override
public void onCreate() {
    super.onCreate();

    mInstance = this;
}

public static synchronized MyApplication getInstance() {
    return mInstance;
}

public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
    ConnectivityReceiver.connectivityReceiverListener = listener;
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

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

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name=".ConnectivityReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

</application>

MainActivity.java

public class MainActivity extends AppCompatActivity
    implements ConnectivityReceiver.ConnectivityReceiverListener {

private Button btnCheck;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    btnCheck = (Button) findViewById(R.id.btn_check);

    // Manually checking internet connection
    checkConnection();

    btnCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Manually checking internet connection
            checkConnection();
        }
    });
}

// Method to manually check connection status
private void checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected();
    showSnack(isConnected);
}

// Showing the status in Snackbar
private void showSnack(boolean isConnected) {
    String message;
    int color;
    if (isConnected) {
        message = "Good! Connected to Internet";
        color = Color.WHITE;
    } else {
        message = "Sorry! Not connected to internet";
        color = Color.RED;
    }

    Snackbar snackbar = Snackbar
            .make(findViewById(R.id.fab), message, Snackbar.LENGTH_LONG);

    View sbView = snackbar.getView();
    TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
    textView.setTextColor(color);
    snackbar.show();
}

@Override
protected void onResume() {
    super.onResume();

    // register connection status listener
    MyApplication.getInstance().setConnectivityListener(this);
}

/**
 * Callback will be triggered when there is change in
 * network connection
 */
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
    showSnack(isConnected);
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...