修改MainActivity中的代码:
public class MainActivity extends Activity {
private IntentFilter intentFilter ;
private NetworkChangeReceiver networkChangeReceiver ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState) ;
setContentView (R.layout.activity_main);
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
public void onReceive (Context context , Intent intent) {
Toast.makeText (context , "network change" , Toast.LENGTH_SHORT).show() ;
}
}
}
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive (Context context , Intent intent) {
Toast.makeText (context , "network change" , Toast.LENGTH_SHORT).show() ;
}
}
private IntentFilter intentFilter ;
intentFilter.addAction ("android.net.conn.CONNECTIVITY_CHANGE") ;
networkChangeReceiver = new NetworkChangeReceiver () ;
registerReceiver (networkChangeReceiver , intentFilter) ;
@Override
protected void onDestroy () {
super.onDestroy () ;
unregisterReceiver (networkChangeReceiver) ;
}
@Override
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 , "network is available" , Toast.LENGTH_SHORT).show() ;
}
else {
Toast.makeText (context , "network is unavailable" , Toast.LENGTH_SHORT).show () ;
}
}
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE) ;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo () ;
networkInfo.isAvailable()
<manifest
……
>
……
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE">
……
manifest>
BootCompleteReceiver.java
public BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive (Context context , Intent intent) {
Toast.makeText (context , "Boot Complete" , Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<manifest
……
>
……
<uses-permission android:name = "android.permission.RECEIVE_BOOT_COMPLETED">
……
<application
……
>
……
<receiver android:name = ".BootCompleteReceiver">
<intent-filter>
<action android:name = "android.intent.action.RECEIVE_BOOT_COMPLETED"/>
intent-filter>
receiver>
application>
manifest>
name = "android.permission.RECEIVE_BOOT_COMPLETED">
<receiver android:name = ".BootCompleteReceiver">
<intent-filter>
<action android:name = "android.intent.action.RECEIVE_BOOT_COMPLETED"/>
intent-filter>
receiver>