我有一个实现广播接收器的类。我也在这堂课内,我希望能够自动发送短信。这可能吗。我尝试过很多不同的东西,似乎没什么用。也许我做错了什么。但这是我到目前为止的源代码。
public class smsReceiver extends BroadcastReceiver {
private MainActivity main;
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, smsReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Bundle bundle = intent.getExtras();
String str = "";
String phonenumber = "";
String houseNumber ="22";
String message = "Two bedrooms Two Baths";
SmsMessage []msgs = null;
SmsManager sms = SmsManager.getDefault();
if(bundle != null){
Object[]pdus = (Object[])bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i2=0; i2<msgs.length; i2++){
msgs[i2]= SmsMessage.createFromPdu((byte[])pdus[i2]);
phonenumber += msgs[i2].getOriginatingAddress();
str += msgs[i2].getMessageBody().toString();
}
sms.sendTextMessage(phonenumber, null, message, pi, null);
}
}
}
如果我做错了什么,请告诉我。提前谢谢大家。
Logcat错误
06-26 15:49:57.357:ERROR / ContactsProvider(175):无法确定联系人兼容性的默认帐户
06-26 15:49:57.357:ERROR / ContactsProvider(175):android.accounts.AuthenticatorException:bind failure
06-26 15:49:57.357:ERROR / ContactsProvider(175):at android.accounts.AccountManager.convertErrorToException(AccountManager.java:1437)
06-26 15:49:57.357:ERROR / ContactsProvider(175):在android.accounts.AccountManager.access $ 400(AccountManager.java:138)
06-26 15:49:57.357:ERROR / ContactsProvider(175):在android.os.Binder.execTransact(Binder.java:320)
06-26 15:49:57.357:ERROR / ContactsProvider(175):at dalvik.system.NativeStart.run(Native Method)
我的所有错误。
答案 0 :(得分:3)
您的AndroidManifest.xml是否包含SEND_SMS权限?
编辑:尝试这个,看看它是否打印出来:
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, smsReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Bundle bundle = intent.getExtras();
String str = "";
String phonenumber = "";
String houseNumber ="22";
String message = "Two bedrooms Two Baths";
try{
SmsMessage []msgs = null;
SmsManager sms = SmsManager.getDefault();
if(bundle != null){
Object[]pdus = (Object[])bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i2=0; i2<msgs.length; i2++){
msgs[i2]= SmsMessage.createFromPdu((byte[])pdus[i2]);
phonenumber += msgs[i2].getOriginatingAddress();
str += msgs[i2].getMessageBody().toString();
}
sms.sendTextMessage(phonenumber, null, message, pi, null);
}
}catch(Exception e1){
android.util.Log.v("SMS ERROR","Exception sending SMS ["+e1.getMessage()+"]", e1);
}
}
答案 1 :(得分:0)
将此块放在广播接收器文件中。
String phonenumber = "123456789";
String message = "Message";
SmsMessage []msgs = null;
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phonenumber, null, message, null, null);
您需要将它放在同一文件中的导入旁边:
import android.telephony.gsm.SmsManager;
您还需要在清单中使用此权限:
<uses-permission android:name="android.permission.SEND_SMS" />
我希望这有帮助!