我有2个动作发生在onreceive方法上,我需要类扩展broadcastreceiver,我不能发送短信因为它必须扩展活动,我想让短信自动重播所以它必须在onreceive方法,我也接受消息并将其转换为语音,两个动作中的每一个都在切换按钮我已经做了转换动作,我可以注册和取消注册接收器,但它无法发送自动回复短信。如果你请回答我
答案 0 :(得分:0)
以下代码自动发送短信 广播接收器类
public class SMSReceiver extends BroadcastReceiver {
private static final String msg="talk u later";
/**
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
String pno=smsMessage[0].getOriginatingAddress();
// show first message
Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
sendSms(pno,msg);
}
private void sendSms(String phonenumber,String message)
{
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(phonenumber, null, message, null, null);
}
}
接收者活动
public class receiver extends Activity {
/** Called when the activity is first created. */
private int status=-1;
SMSReceiver receiver=null;
IntentFilter filter=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startLogic();
}
//====================================================
private void changeReceiverStatus(int status){
try{
if(receiver==null)
receiver=new SMSReceiver();
if(filter==null){
filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
}
if(status<0)
this.unregisterReceiver(receiver);
else
this.registerReceiver(receiver, filter);
}catch(Exception e){e.printStackTrace();}
}
//====================================================
private void startLogic(){
try{
final Handler handler=new Handler(){
public void handleMessage(Message msg){
try{
int status=msg.getData().getInt("status");
if(status<0)
Toast.makeText(receiver.this, "Unregistering receiver for 20 sec", Toast.LENGTH_SHORT).show();
else
Toast.makeText(receiver.this, "Registering receiver for 20sec", Toast.LENGTH_SHORT).show();
}catch(Exception e){e.printStackTrace();}
}};
new Thread(){
public void run(){
try{
while(true){
Bundle b=new Bundle();
b.putInt("status", status);
Message msg=new Message();
msg.setData(b);
handler.sendMessage(msg);
changeReceiverStatus(status);
status=status*-1;
Thread.sleep(20000);
}
}catch(Exception e){e.printStackTrace();}
}}.start();
}catch(Exception e){e.printStackTrace();}
}
}
希望它会有所帮助!!