如何在android中接收短信

时间:2014-01-27 05:30:04

标签: android sms

我正在使用短信开发一个应用程序,我可以成功接收短信但我的要求是显示对话框5分钟等待接收短信,并且在5分钟时间如果短信接收然后显示对话框消失了。我有关于asynctask的想法但我不知道如何使用请告诉我

我的代码是

SmsBroadCast

public class SmsBroadCast extends BroadcastReceiver{

private String body ="" ;
String ContactNumber;
 SmsMessage[] sms;

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
     Bundle bundle=intent.getExtras();

        Object[] messages=(Object[])bundle.get("pdus");
        sms =new SmsMessage[messages.length];

        for(int n=0;n<messages.length;n++){
            sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
        }

        for(SmsMessage msg:sms) {
            ContactNumber = msg.getOriginatingAddress();
             body         = msg.getMessageBody();

             if (sms.length > -1) {
                    Log.i("receive", "Message : " + sms[0].getMessageBody());
                    MainActivity.updateMessageBox(
                            body);

           }
        }
          }
        }

 MainActivity

public class MainActivity extends Activity {

static TextView show ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    show = (TextView)findViewById(R.id.showBox);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public static void updateMessageBox(String msg) {

    show.setText(msg); 

}

 }

1 个答案:

答案 0 :(得分:0)

公共类IncomingSms扩展了BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                String senderNum = phoneNumber;
                String message = currentMessage.getDisplayMessageBody();

                Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);


               // Show Alert
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, 
                             "senderNum: "+ senderNum + ", message: " + message, duration);
                toast.show();

            } // end for loop
          } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" +e);

    }
}    

}