android 8.0以后大部分静态监听无法注册,需要注册动态监听

拿监听网络状态来举例子

动态注册网络监听
AndroidManifest中添加权限


    

网络监听代码块

public class NetWorkChangeReceiver extends BroadcastReceiver {
    public NetWorkChangeReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("mile","come in NetWorkChangeReceiver onReceive");
        // TODO: This method is called when the BroadcastReceiver is receiving
        //Toast.makeText(context,"netChanged!",Toast.LENGTH_LONG).show();
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo !=null && networkInfo.isAvailable())
        {
            Toast.makeText(context,"isAvailable!",Toast.LENGTH_LONG).show();
        }else
        {
            Toast.makeText(context,"unAvailable!",Toast.LENGTH_LONG).show();
        }
    }
}
public class YuloreApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        NetWorkChangeReceiver netWorkStateReceiver = new NetWorkChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
    }
}

你可能感兴趣的:(android,php,开发语言)