android---四大组件广播 来监听网络变化

1在activity中注册系统的广播  

intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
package com.yifei.myapplication;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    public static  String TAG ="MainActivity12";
    private MyService myService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //系统的检测网络的广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        myService = new MyService();
        registerReceiver(myService, intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myService);
    }
}

在广播中监听

package com.yifei.myapplication;

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

public class MyService extends BroadcastReceiver {
    public static final String receiver = "com.yifei.myapplication.MyService";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(MainActivity.TAG, "onReceive: MyService");
        //获取到系统管理网络的管理者
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            Toast.makeText(context, "当前存在网络", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(context,"没有网络",Toast.LENGTH_SHORT).show();
        }

    }
}

mainifest.xml 网络权限

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值