本文实例为大家分享了Android学习之Broadcast的使用方法,供大家参考,具体内容如下实现开机启动提示网络的广播package com.example.luobo.broadcasttest;import android.conte
本文实例为大家分享了Android学习之Broadcast的使用方法,供大家参考,具体内容如下
实现开机启动提示网络的广播
package com.example.luobo.broadcasttest;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.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast;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");//添加接收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) { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);//通过此方法获取ConnectivityManager实例 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();//调用实例connectivityManager的getActiveNetworkInfo()方法获取NetworkInfo实例 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(); } } }}
--结束END--
本文标题: Android学习之Broadcast的简单使用
本文链接: https://lsjlt.com/news/221710.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0