【问题标题】:Using sharedpref strings as inputs into sendTextMessage使用 sharedpref 字符串作为 sendTextMessage 的输入
【发布时间】:2012-09-06 20:44:26
【问题描述】:

我正在创建一个应用程序,它接受用户通过 EditText 输入的字符串,将它们放入共享首选项中,然后在收到短信时发送自动短信,使用来自共享首选项的字符串来指示电话号码和短信会自动发送。

只要我硬编码电话号码和要发送的短信,该应用程序就可以完美运行。一旦我尝试将共享首选项中的字符串放入 SendSMS 方法中,应用程序就会崩溃,并且出现调试错误“hasUserDataHeader:false”

下面的代码是我尝试从名称 EditText 中获取字符串并将其用作要通过参数 TextMessage 发送的消息的版本(请参阅广播接收器中的这行代码)。如果我用“TextMessage”替换它,那会很好,但显然这不会使发送的文本动态

代码如下:

                import android.os.Bundle;
            import android.app.Activity;
            import android.view.Menu;
            import android.view.View;
            import android.widget.AdapterView;
            import android.widget.AdapterView.OnItemSelectedListener;
            import android.widget.ArrayAdapter;
            import android.widget.EditText;
            import android.widget.Spinner;
            import android.widget.Button;
            import android.app.PendingIntent;
            import android.content.Intent;
            import android.telephony.SmsManager;
            import android.content.BroadcastReceiver;
            import android.content.Context;
            import android.content.IntentFilter;
            import android.widget.TextView;
            import android.app.Notification;
            import android.app.NotificationManager;
            import android.content.SharedPreferences;

            public class MainActivity extends Activity {

                int notificationID = 1;
                String[] excuses;
                String excuseSelected;
                IntentFilter intentFilter;
                private SharedPreferences prefs;
                private String prefName = "MyPref";
                private static final String NUMBER_KEY = "number";
                private static final String NAME_KEY = "name";
                private static final String EXCUSE_KEY = "excuse"; 


                private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {

                        //---gather up all the necessary user input---
                        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                        String textMessage = (String) prefs.getString(NAME_KEY, "");
                        sendSMS("0403579838", textMessage);             
            //          }
                    }
                };

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

                    //---intent to filter for SMS messages received---
                    intentFilter = new IntentFilter();
                    intentFilter.addAction("SMS_RECEIVED_ACTION");

                    final Button btn1 = (Button)findViewById(R.id.buttonToggle);

                    excuses = getResources().getStringArray(R.array.excuses_array);
                    Spinner s1 = (Spinner) findViewById(R.id.spinnerExcuse);
                    final EditText EditTextNumber = (EditText) findViewById(R.id.editTextNumber);
                    final EditText EditTextName = (EditText) findViewById(R.id.editTextName);



                        //---Sorting the spinner view out for excuses selection---
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                android.R.layout.simple_spinner_item, excuses);

                        s1.setAdapter(adapter);
                        s1.setOnItemSelectedListener(new OnItemSelectedListener()
                        {
                            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                    int arg2, long arg3)
                            {
                                int index = arg0.getSelectedItemPosition();
                                excuseSelected = excuses[index];
                            }

                            public void onNothingSelected(AdapterView<?> arg0) {}
                        });

                    //---Setting the button to toggle between on and off---
                    btn1.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            if (btn1.getText().equals("Turn on"))                       
                            {
                                btn1.setText("Turn off");
                                //---register the receiver---
                                registerReceiver(intentReceiver, intentFilter);
                                //---get the SharedPreferences object---
                                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                                SharedPreferences.Editor editor = prefs.edit();

                                //---set the user inputs to prefo's---
                                editor.putString(NUMBER_KEY, EditTextNumber.getText().toString());
                                editor.putString(NAME_KEY, EditTextName.getText().toString());
                                editor.putString(EXCUSE_KEY, excuseSelected);

                            }
                            else
                            {
                                btn1.setText("Turn on");
                                //---unregister the receiver---
                                unregisterReceiver(intentReceiver);
                            }
                        }
                    });

                }

                //---sends an SMS message to another device---
                public void sendSMS(String phoneNumber, String message)
                {
                    SmsManager sms = SmsManager.getDefault();
                    sms.sendTextMessage(phoneNumber, null, message, null, null);
                    displayNotification();
                }

                protected void displayNotification()
                {
                    Intent i = new Intent(this, NotificationView.class);
                    i.putExtra("notificationID", notificationID);

                    PendingIntent pendingIntent =
                        PendingIntent.getActivity(this, 0, i, 0);

                    NotificationManager nm = (NotificationManager)
                        getSystemService(NOTIFICATION_SERVICE);

                    Notification notif = new Notification(
                            R.drawable.ic_launcher,
                            "SMS has been sent by GirlfriendMinder",
                            System.currentTimeMillis());

                    CharSequence from = "GirlfriendMinder";
                    CharSequence message = "SMS has been sent by GirlfriendMinder";

                    notif.setLatestEventInfo(this, from, message, pendingIntent);

                    //---100ms delay, vibrate for 250ms, pause for 100ms, and then vibrate for 500ms---
                    notif.vibrate = new long[] { 100, 250, 100, 500};
                    nm.notify(notificationID, notif);
                }

                @Override
                protected void onDestroy() {
                    //---unregister the receiver---
                    unregisterReceiver(intentReceiver);
                    super.onPause();
                }
            }

【问题讨论】:

  • 你想从哪里获取消息和电话号码来发送短信?

标签: android sms


【解决方案1】:

在您的代码中:

//---Setting the button to toggle between on and off---
                    btn1.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            if (btn1.getText().equals("Turn on"))                       
                            {
                                btn1.setText("Turn off");
                                //---register the receiver---
                                registerReceiver(intentReceiver, intentFilter);
                                //---get the SharedPreferences object---
                                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                                SharedPreferences.Editor editor = prefs.edit();

                                //---set the user inputs to prefo's---
                                editor.putString(NUMBER_KEY, EditTextNumber.getText().toString());
                                editor.putString(NAME_KEY, EditTextName.getText().toString());
                                editor.putString(EXCUSE_KEY, excuseSelected);

                            }
                            else
                            {
                                btn1.setText("Turn on");
                                //---unregister the receiver---
                                unregisterReceiver(intentReceiver);
                            }
                        }
                    });

                }

下面:

editor.putString(EXCUSE_KEY, excuseSelected);

添加

editor.commit();

【讨论】:

  • 谢谢。这适用于 textMessage。但是,如果我尝试做同样的事情并使电话号码动态化,通过使用说 String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");发送短信(电话号码,短信);然后我仍然得到同样的错误。有什么想法吗?
  • 实际上它不应该发生,一旦你提交你的 SharedPreference.Editor 对象,它就会被优先存储,你会得到你存储它的所有数据。
  • 我认为问题出在 PhoneNumber 的变量类型上 -> 当用户输入“0400111111”而不是 0401111111 时,它会起作用。我将构建一些额外的代码以确保将数字转换为字符串。感谢您对 SharedPreferences Mohit 的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多