2
我想開發一個短信應用程序,它在收到短信時用自定義文本發送自動短信到「短信發送者」。 首先,我創建了廣播接收器類在android中發送自動短信
public class MyBroadCastReceiver extends BroadcastReceiver {
private final String MSG_BODY="Thank you for contact we will contact u later";
final int MAX_SMS_MESSAGE_LENGTH=160;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
{
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
}
Toast.makeText(context, "SMS sent",
Toast.LENGTH_SHORT).show();
//String msgBody = msgs[i].getMessageBody();
msg_from = msgs[0].getOriginatingAddress();
sendSms(msg_from,MSG_BODY);
}
catch(Exception e){Log.d("Exception caught",e.getMessage());}
}
}
}
private void sendSms(String phonenumber,String message)
{
SmsManager manager = SmsManager.getDefault();
int length = message.length();
if(length > MAX_SMS_MESSAGE_LENGTH)
{
ArrayList<String> messagelist = manager.divideMessage(message);
manager.sendMultipartTextMessage(phonenumber, null, messagelist, null, null);
}
else
{
manager.sendTextMessage(phonenumber, null, message, null, null);
}
}
}
而且清單文件是
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:enabled="true"
android:name="com.myapp.MyBroadCastReceiver">
</receiver>
<activity android:name=".MeraSms"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>
它什麼都不做只顯示我的主要活動。 幫助我,我錯了。
嗯,我再次運行它,它工作一流。 – Sunny