我的应用程序仅在移动网络可用时才发送短信。 目前我已经设置了ON WIFI以及MOBILE NETWORK。
执行时的以下代码段给出了:
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
}
答案 0 :(得分:0)
此代码应该可以帮助您检测不同的状态
TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
int simCardState = telMgr.getSimState();
switch (simCardState) {
case TelephonyManager.SIM_STATE_ABSENT:
// do something
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
// do something
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
// do something
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
// do something
break;
case TelephonyManager.SIM_STATE_READY:
// here you may set a flag that the phone is ready to send SMS
break;
case TelephonyManager.SIM_STATE_UNKNOWN:
// do something
break;
}