1

哦,伙计,我已经用谷歌搜索了我的裤子,几天来都没有遇到错误。

简而言之,我想收到一条带有消息设备的短信:命令,例如 SPA:ON

我的应用程序非常简单,我要做的就是更改在 MainActivity 中显示设备状态的文本(即更改 XML 中的 @string/somevalue),以便当我收到 SPA:ON 消息时,我的 TextView从 OFF 的初始字符串变为 ON 的新命令文本。

鉴于下面的代码,最好的方法是什么?

如果不可能 - 我该怎么办?

谢谢

public class MainActivity extends Activity {

    private static Button buttonSend;
    private static EditText textPhoneNo;
    private static EditText textSMS;
    private static Context context;

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

        buttonSend = (Button) findViewById(R.id.buttonSend);
        textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
        textSMS = (EditText) findViewById(R.id.editTextSMS);

        buttonSend.setOnClickListener(new OnClickListener() {

            @Override
        public void onClick(View v) {   

            String phoneNo = textPhoneNo.getText().toString();
            String sms = textSMS.getText().toString();  

            if (phoneNo.length()>0 && sms.length()>0) 
            {
                sendSMS(phoneNo, sms);
            }
            else
            {
                Toast.makeText(getBaseContext(), 
                    "Please enter both phone number and message.", 
                    Toast.LENGTH_SHORT).show();
            }
        }
        });
    }  

    //---sends a SMS message to another device---
    public void sendSMS(String phoneNo, 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 context, Intent intent) {
                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 context, Intent intent) {
                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));         

        try 
        {
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);
        } 
    catch (Exception e) 
        {
            Toast.makeText(getApplicationContext(),
                "SMS faild, please try again.",
                Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }       
}

要接收(并尝试进行文本更新)的 SMS 代码是:

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 = "";    

    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]);                
            str += "SMS from :" + msgs[i].getOriginatingAddress();                     
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";        
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_LONG).show(); 

        //---update the device status from the command---
        /* SOME HOW I WANT TO DO:

        String toast_msg = "None";
        String temp[];
        temp = str.split("\\:");
        String device = temp[0];
        String cmd = temp[1];

        TextView t = (TextView) findViewById(R.id.textViewSPAStatus);

        t.setText(cmd);

        Toast.makeText(getBaseContext(), 
                toast_msg, 
                Toast.LENGTH_SHORT).show(); 
        */
    }                       
}
}
4

1 回答 1

0

您不能修改 xml,这些值对于 xml 是永久的。您可以改用什么:

  • 共享首选项
  • SQLite 数据库
  • 一份文件

SharedPreferences是最简单的设置并且运行良好,虽然文本 Preferences 是名称的一部分,但它不限于设置,因为它是一个简单的键值对存储选项。因此,在设置之后,您的应用程序将使用它作为集中的“命令文本”数据库。这意味着当您的 Activity 创建/恢复时,您将使用 SharedPreferences 的任何内容更新 TextView。SharedPreferences 的好处在于您可以为您的命令创建一个单独的简单数据库,除非用户删除您的应用程序数据,否则它是您的应用程序需要在重启、退出等期间持久保存的值的最安全存储选项之一。

此外,为了确保您的接收者可以接收所有消息,您可能需要考虑创建一个后台服务来注册您的接收者。

于 2012-12-06T02:08:43.313 回答