0

我想接收短信并显示对话框。我怎样才能做到这一点?

短信接收者:

public class SMSReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        String num = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            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]);
                if (i==0) {
                    //---get the sender address/phone number---
                    num += msgs[i].getOriginatingAddress();
                } 
                //---get the message body---
                str += msgs[i].getMessageBody().toString();                    
            }
            //---display the new SMS message---
            if (num.equals("+XXXXXXXXX")){
                Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
               //What to do here?
            }

            //---prevent this SMS message from being broadcasted---
            abortBroadcast();
            Log.d("SMSReceiver", str);            
        }
    }
}

我的主要:

public class MainActivity extends FragmentActivity implements YesNoDialogListener {

    GoogleMap googleMap;

    Marker marker = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        }
        else {    // Google Play Services are available
            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();
            // get my actual position and display a blue dot
            googleMap.setMyLocationEnabled(true);
            Location myLocation = googleMap.getMyLocation();

            if( myLocation != null ){
                Toast.makeText(this, "Latitude: " + myLocation.getLatitude() + "\nLongitude: " + myLocation.getLongitude(), Toast.LENGTH_SHORT).show();
            }
            if( myLocation == null ){
                Toast.makeText(this, "Chujnia", Toast.LENGTH_SHORT).show();
            }
        }

    }

    //==Dialog yes/no
    public void btnShowYesNoDialog(View view) {
        showYesNoDialog();
    }

    public void showYesNoDialog() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        YesNoDialogFragment yesnoDialog = new YesNoDialogFragment();
        yesnoDialog.setCancelable(false);
        yesnoDialog.setDialogTitle("New accident");
        yesnoDialog.show(fragmentManager, "yes/no dialog");
    }

    @Override
    public void onFinishYesNoDialog(boolean state) {
        Toast.makeText(this, "Returned from dialog: " + state, 
        Toast.LENGTH_SHORT).show();
        SmsManager sms = SmsManager.getDefault();
        if (state == true){
            sms.sendTextMessage("+XXXXXX", null, "OK", null, null);
        }
        else{
            sms.sendTextMessage("+XXXXXXX", null, "No", null, null);
        }
    }

}

如何从 SmsReceive 执行 btnShowYesNoDialog?现在它只有在我按下连接到 btnShowYesNoDialog 的按钮时才有效?

4

2 回答 2

0

您可以将 SMSReceiver 放入 MainActivity :

public class MainActivity extends FragmentActivity implements YesNoDialogListener {

    private BroadcastReceiver SMSReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
              //TODO
        }
    };
}

记得注册广播接收器


更新。对不起。我没有仔细阅读你的代码。我认为你需要android application

public class MyApplication extends Application{
    private static MyApplication instance;
    public static MyApplication getInstance(){
        return instance;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}

机器人清单:

<application
    android:name="xx.xx.MyApplication">

然后您可以在 onReceive 方法中显示 Toast 或对话框:

Toast.makeText(MyApplication.getInstance(), "ok", Toast.LENGTH_LONG).show();
于 2013-07-28T03:31:05.773 回答
0

如果您需要在应用程序打开期间接收短信(不是作为服务),您可以将 Receiver 放在主要活动中,如 hewwcn 回答中所述。

例如:

public class MainActivity extends Activity {

    /*
     * Variables for BroadcastReceiver
     */
    boolean isRegistered = false; // check if BroadcastReceiver registered
    private IntentFilter filterSmsReceived = new IntentFilter(
            "android.provider.Telephony.SMS_RECEIVED");

    /**
     * Create BroadcastReceiver
     */
    private BroadcastReceiver smsReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(
                    "android.provider.Telephony.SMS_RECEIVED")) {
                /* get the SMS message passed in */
                Bundle bundle = intent.getExtras();

                SmsMessage[] msgs = null;
                String msgFrom = null;
                String msgBody = null;
                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]);
                            msgFrom = msgs[i].getOriginatingAddress();
                            msgBody = msgs[i].getMessageBody();
                        }                   

                        /* 
                         * TODO Show dialog 
                         */


                    } catch (Exception e) {
                        // Log.d("Exception caught",e.getMessage());
                    }
                }
            }
        }
    };

    /**
     * Button - register BroadcastReceiver when clicked (or put it to onCreate)
     */
    public void onButtonClicked(View v) {
        this.registerReceiver(smsReceiver, filterSmsReceived);
        isRegistered = true;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onPause() {
        /* 
         * Unregister BroadcastReceiver
         */
        if (isRegistered) {
            this.unregisterReceiver(smsReceiver);
            isRegistered = false;
        }
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        /* 
         * Unregister BroadcastReceiver
         */
        if (isRegistered) {
            this.unregisterReceiver(smsReceiver);
            isRegistered = false;
        }
        super.onDestroy();

    }

}
于 2013-07-29T08:50:16.860 回答