如何从一个特定号码接收短信(其他短信转到手机的收件箱)

时间:2012-10-28 11:14:28

标签: android android-intent sms broadcastreceiver

我的程序可以成功发送和接收短信。现在,我希望仅通过特定的电话号码在我的程序中接收短信,而来自所有其他号码的短信则转到手机的收件箱。我使用的代码如下。它不起作用,每条短信都会进入手机的收件箱。我认为msg_from方法中的SmsReceiver无法在for循环中获得价值且始终为null

MainActivity .java

  public class MainActivity extends Activity {
             private TextView showSms;
                private String   ReceivedSms;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                super.onCreate(savedInstanceState);
                // _smsReceiver.onReceive(getBaseContext(), getIntent());
                setContentView(R.layout.activity_main);
                Intent _intent = getIntent();
                ReceivedSms = _intent.getStringExtra("message");
                showSms = (TextView) this.findViewById(R.id.txt_Show);
                showSms.setText(ReceivedSms);
            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                getMenuInflater().inflate(R.menu.activity_main, menu);
                return true;
            }
        }

SmsReceiver .java

public class SmsReceiver extends BroadcastReceiver {
    public String str = "";

    @Override
    public void onReceive(Context context, Intent intent) {
        // ---get the SMS message passed in---

        Bundle bundle = intent.getExtras();
        Object messages[] = (Object[]) bundle.get("pdus");
        SmsMessage[] msgs = null;

        if (bundle != null)
        {

            Object[] pdus = (Object[]) bundle.get("pdus");
            SmsMessage smsMessage[] = new SmsMessage[messages.length]; 
           //msgs = new SmsMessage[pdus.length];
            String msg_from[]=null;
            for (int n = 0; n < messages.length; n++) 
            {
                smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); 
                  msg_from[n] = msgs[n].getOriginatingAddress();
            }


            if(msg_from .equals("+9856874236"))  
            {
            for (int n = 0; n < messages.length; n++) 
            {

                smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]); 
                str += "SMS from " + msgs[n].getOriginatingAddress();
                str += " :";
                str += msgs[n].getMessageBody().toString();

                str += "\n";

           abortBroadcast();

           }
           Intent act = new Intent(context, MainActivity.class);
            act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            act.putExtra("message", str);
            context.startActivity(act);
        }

        }

    }
}

的Manifest.xml

<uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>

<uses-permission android:name="android.permission.READ_SMS" />
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity"
                  android:label="@string/app_name"/>
       <receiver
            android:name="com.example.sms.SmsReceiver"
            class="com.example.sms.SmsReceiver" >
            <intent-filter android:priority="100" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>  
    </application>  

sms.java

public class SMS extends Activity {

     Button btnSendSMS;
        EditText txtPhoneNo;
        EditText txtMessage;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);        

            btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
            txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
            txtMessage = (EditText) findViewById(R.id.txtMessage);

            btnSendSMS.setOnClickListener(new View.OnClickListener() 
            {
                public void onClick(View v) 
                {                
                    String phoneNo = txtPhoneNo.getText().toString();
                    String message = txtMessage.getText().toString();                 
                    if (phoneNo.length()>0 && message.length()>0)                
                        sendSMS(phoneNo, message);                
                    else
                        Toast.makeText(getBaseContext(), 
                            "Please enter both phone number and message.", 
                            Toast.LENGTH_SHORT).show();
                }
            });        
        } 
        private void sendSMS(String phoneNumber, String message)
        {        
            String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";

            PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

            PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

            //---when the SMS has been sent---
            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(getBaseContext(), "SMS sent", 
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(getBaseContext(), "Generic failure", 
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_NO_SERVICE:
                            Toast.makeText(getBaseContext(), "No service", 
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            Toast.makeText(getBaseContext(), "Null PDU", 
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            Toast.makeText(getBaseContext(), "Radio off", 
                                    Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            }, new IntentFilter(SENT));

            //---when the SMS has been delivered---
            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(getBaseContext(), "SMS delivered", 
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case Activity.RESULT_CANCELED:
                            Toast.makeText(getBaseContext(), "SMS not delivered", 
                                    Toast.LENGTH_SHORT).show();
                            break;                        
                    }
                }
            }, new IntentFilter(DELIVERED));        

            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
        }

}

main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Enter the phone number of recipient" />

        <EditText
            android:id="@+id/txtPhoneNo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Message" />

        <EditText
            android:id="@+id/txtMessage"
            android:layout_width="fill_parent"
            android:layout_height="150px"
            android:gravity="top" />

        <Button
            android:id="@+id/btnSendSMS"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send SMS" />

        <TextView
            android:id="@+id/txt_Show"
            android:layout_width="119dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.11"
            android:text="@string/soha" />
    </LinearLayout>

</RelativeLayout>

0 个答案:

没有答案