1》判断网络状态网络广播(动态注册)
package com.example.guangbo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.nio.channels.NetworkChannel;
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter=new IntentFilter();
intentFilter.addAction(“android.net.conn.CONNECTIVITY_CHANGE”);//网络变化是会发送该广播
networkChangeReceiver=new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
//在网络发生变化时,onReceive会被调用
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isAvailable()){
Toast.makeText(context,“网络可用”,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,“网络不可用”,Toast.LENGTH_SHORT).show();
}
}
}
}
//由于涉及到权限问题,所以需要在AndroidMainfest.xml中添加如下注册代码
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
在网络发生变化时,手机便会出现提示
1》接收开机广播(静态注册)
New-》others-》Broadcast Receiver可以快速创建广播
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context,“开机成功”,Toast.LENGTH_SHORT).show();
}
AndroidMainfest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>//加入新的权限
<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>