您是否包括了这些权限?
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
并确保检查它们是否适用于 Android M 以上的设备:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
//All Permissions are granted
return true;
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.SEND_SMS}, YOURPERMISSIONRESULTCODEINT);
//permissions are not granted so this check has failed
return false;
}
}
//The device is <Android M and so manifest declarations should be enough
return true;
}
重复此操作或为字符串数组中的每个权限添加单独检查(这将创建一个权限组)。
对于您的网络管理员:
LocationManager locationManager = (LocationManager) context
.getSystemService(context.LOCATION_SERVICE);
// getting network status
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
一些短信细节:
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
final SmsManager smsManager = SmsManager.getDefault();
//Allows you to detect when an SMS has been sent via an application wide broadcast
final PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
new Intent(SENT), 0);
//Same as above but is instead when it is delivered
final PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
new Intent(DELIVERED), 0);
然后在 SMS 发送后或发送期间注册广播接收器:
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered else this code won't run---
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
//Then send your message
smsManager.sendTextMessage("phoneNumber", null, "Message", sentPI, deliveredPI);
}