我的应用程序仅在移动网络可用时才发送 SMS。目前我已经设置了 WIFI 并且存在移动网络。
执行时的以下代码片段给了我:
public boolean isNetworkAvailable(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// WIFI is ON and MOBILE Network is present.
final NetworkInfo mobileNetwork = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
final State mobileState = mobileNetwork.getState();
if(mobileNetwork!=null)
{
// RETURNS FALSE
Log.d("Contacts","mobileNetwork.isConnected() "+mobileNetwork.isConnected());
// RETURNS FALSE
Log.d("Contacts","isConnectedOrConnecting() "+mobileNetwork.isConnectedOrConnecting());
// RETURNS TRUE
Log.d("Contacts","mobileNetwork.isAvailable()() "+mobileNetwork.isAvailable());
return mobileNetwork.isAvailable();
}
return false;
}
问题是现在如何根据以上三行返回的值来检测我是否可以发送短信?
由于 isAvailable() 返回 true 而其他 2 行返回 false;
解决方案
我想出了这个代码:
TelephonyManager telMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
int simCardState = telMgr.getSimState();
int simNetworkType = telMgr.getNetworkType();
int simDataState = telMgr.getDataState();
if(simCardState == TelephonyManager.SIM_STATE_READY && simDataState == TelephonyManager.DATA_CONNECTED)
{
//NETWORK IS AVAILABLE FOR SENDING SMS
}