保存用户在共享首选项中输入的文本,并在另一个活动中使用它

时间:2014-03-03 17:50:33

标签: android save broadcastreceiver sharedpreferences android-edittext

我正在创建一个应用,用户需要输入文字。此文本将保存在应用程序中,稍后将在用户收到SMS时使用。现在,当我点击保存按钮时,应用程序崩溃了。这是我的代码:

MainActivity.java

public class MainActivity extends Activity {
Context Context;
AudioManager am;
Button save;
EditText on;
EditText off;
SharedPreferences saved;

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

    save = (Button) findViewById(R.id.button1);
    on = (EditText) findViewById(R.id.on);
    off = (EditText) findViewById(R.id.off);
    save.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
                            Toast.makeText(getApplicationContext(), "Saved!",
                       Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(MainActivity.this, SMSReceiver.class);
            String[] myStrings = new String[] { on.getText().toString(),
                    off.getText().toString() };
            intent.putExtra("strings", myStrings);

            SharedPreferences preferences = getSharedPreferences("saved",
                    MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("text1", on.getText().toString());
            editor.putString("text2", off.getText().toString());
            editor.commit();
            sendBroadcast(intent);
        }
    });
}
}

SMSReceiver.java:

public class SMSReceiver extends BroadcastReceiver {

Context Context;
AudioManager am;
SharedPreferences settings;
String text1;
String text2;

public void onEnabled(Context ctx) {
    settings = ctx.getSharedPreferences("saved", 0);
    text1 = settings.getString("text1", " ");
    text2 = settings.getString("text2", " ");       
}

@Override
public void onReceive(Context context, Intent intent) {
    this.Context = context;
    if (intent.getAction()
            .equals("android.provider.Telephony.SMS_RECEIVED")) {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        if (bundle != null) {
            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]);
                String msgBody = msgs[i].getMessageBody();
                if (msgBody.equals(text1)) {
                Toast.makeText(getApplicationContext(), "First",
                       Toast.LENGTH_SHORT).show();
                }
                if (msgBody.equals(text2)) {
                Toast.makeText(getApplicationContext(), "Second",
                       Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
}

这是logcat:

03-03 23:06:32.456: E/AndroidRuntime(1229): FATAL EXCEPTION: main
03-03 23:06:32.456: E/AndroidRuntime(1229): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{pv.ilostmyphone/pv.ilostmyphone.Broadcast.SMSReceiver}: java.lang.ClassCastException: pv.ilostmyphone.Broadcast.SMSReceiver
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.os.Looper.loop(Looper.java:130)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at java.lang.reflect.Method.invoke(Method.java:507)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at dalvik.system.NativeStart.main(Native Method)
03-03 23:06:32.456: E/AndroidRuntime(1229): Caused by: java.lang.ClassCastException: pv.ilostmyphone.Broadcast.SMSReceiver
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-03 23:06:32.456: E/AndroidRuntime(1229):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
03-03 23:06:32.456: E/AndroidRuntime(1229):     ... 11 more

第二个问题

收到短信时没有发生任何事情。我的MainActivity.java位于包“pv.ilostmyphone”中,而SMSReceiver.java位于包“pv.ilostmyphone.Broadcast”中。这是我的清单中的接收器部分:

    <receiver android:name=".Broadcast.SMSReceiver" >
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            <action android:name="pv.ilostmyphone.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

这是我在MainActivity.java中创建的新意图:

Intent intent = new Intent("pv.ilostmyphone.SMS_RECEIVED");
            String[] myStrings = new String[] { on.getText().toString(),
                    off.getText().toString() };
            intent.putExtra("strings", myStrings);

            SharedPreferences preferences = getSharedPreferences("saved",
                    MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("text1", on.getText().toString());
            editor.putString("text2", off.getText().toString());
            editor.commit();
            sendBroadcast(intent);

2 个答案:

答案 0 :(得分:1)

startActivity(intent)替换为sendBroadcast(intent)。您尝试使用映射到Activity Intent的{​​{1}}开始BroadcastReceiver是没有意义的。

答案 1 :(得分:1)

这条线是罪魁祸首。
    Intent intent = new Intent(MainActivity.this,SMSReceiver.class);

您正在拨打ActivityBroadcastReceiver的电话。因此,它抛出ClassCastException

从您的活动发送广播:

Intent intent = new Intent("packagename.MY_ACTION");    
sendBroadcast(intent);

在manifest.xml文件中,使用此广播名称定义intent-filter。通过这种方式,当触发此特定广播时,将调用BroadcastReceiver。

<receiver android:name="ReceiverName" >
        <intent-filter>
            <action android:name="packagename.MY_ACTION" />
        </intent-filter>
</receiver>    

<强> [编辑]
第二个问题的解决方案在于清单文件本身。在BroadcastReceiver的intent-filter列表中添加以下操作。

<action android:name="android.provider.Telephony.SMS_RECEIVED" />    

不要忘记添加在清单文件中接收短信的权限。