Action 為 ConnectivityManager.CONNECTIVITY_ACTION
以下程式碼示範如何判斷目前是否有連線能力與是否使用 3G 網路
private BroadcastReceiver mConnectivityReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(final Context context, Intent intent)
{
final String action = intent.getAction();
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
{
boolean noConnectivity, useMobileNetwork;
noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
final NetworkInfo mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
useMobileNetwork = mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
final String msg = "Connect:" + noConnectivity + "\nUse3G:" + useMobileNetwork;
}
}
}
public void onCreate()
{
final IntentFilter f = new IntentFilter();
f.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mConnectivityReceiver, f);
}
此外使用網路要記得在 manifast 中加入 permission 哦
<uses-permission android:name="android.permission.INTERNET" />
沒有留言:
張貼留言