如何在Android中获取传入的短信?

时间:2015-05-06 07:29:05

标签: android broadcastreceiver android-manifest android-broadcast

我想在其他设备发送短信时打印Toast消息。我写了代码。但它不起作用。请任何人帮助我。 android版本:4.0.4 MainActivty:

public class MainActivity extends ActionBarActivity {
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
    BroadcastReceiver receiver = new SmsReceiver();

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter("some_string-to_call_receiver");
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected 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);

        sendBroadcast(new Intent("some_string-to_call_receiver"));

    }
}

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sms" >
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>
    <receiver android:name=".SmsReceiver">
        <intent-filter>
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

</manifest>

smsreceiver:

public class SmsReceiver   extends BroadcastReceiver {
    public static String SERVER_SUCCESS_CODE = "";

    // 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();
                    String[] split_one = message.split(":");
                    String  ss = split_one[1].substring(0, 4);
                    if(ss.length()==4)
                    {
                        SERVER_SUCCESS_CODE=ss;
                    }

                    /*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();

                }
            }

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

        }
    }
}

我如何获得传入的短信和吐司打印!

2 个答案:

答案 0 :(得分:1)

使用此代码:

public class IncomingSms extends BroadcastReceiver {
 public static String SERVER_SUCCESS_CODE = "";

// 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();
                String[] split_one = message.split(":");
                String  ss = split_one[1].substring(0, 4);
                if(ss.length()==4)
                {
                    Constants.SERVER_SUCCESS_CODE=ss;
                }

                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();*/

            } 
        } 

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

    }
}
}

不要忘记在manifest.xml中添加权限:

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

答案 1 :(得分:0)

这是我以前读过的短信,从gits Android SMS Receive Listener下载原始文件 实施SMSReceivedListner并添加SMSReceiver.addSMSListner(this);

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import java.util.ArrayList;

/**
 * @@author Chathura Wijesinghe <cdanasiri@gmail.com> 
 * 
 * <receiver android:name=".SMSReceiver" >
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>
 */
public class SMSReceiver extends BroadcastReceiver {

private static final String SMS_RECEIVED         = "android.provider.Telephony.SMS_RECEIVED";

private static ArrayList<SMSReceivedListner> smsListner = new ArrayList<SMSReceivedListner>();

@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    final Bundle extras = intent.getExtras();


    if (action.equals(SMSReceiver.SMS_RECEIVED)) {
        final boolean smsValid = extras != null;

        if (smsValid) {
            //Create SMSMessages from PDUs in the Bundle
            final Object[] pdus = (Object[])extras.get("pdus");
            final SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++)
                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

            //Assemble
            final ArrayList<Long> vibrations = new ArrayList<Long>();

            for (SmsMessage message : messages) {
                for (SMSReceivedListner smsReceivedListner : smsListner )
                    smsReceivedListner.message(message);
            }
        }
    }
}

public static void addSMSListner(SMSReceivedListner listner){
    smsListner.add(listner);
}

public static void removeSMSListner(SMSReceivedListner listner){
    smsListner.remove(listner);
}

public interface SMSReceivedListner{
    public void message(SmsMessage message);
}}