将字符串从Android Java活动传递到广播接收器

时间:2012-08-06 19:35:57

标签: android string broadcastreceiver

我花了最后几个小时来查看关于这个主题的其他问题,但我发现的任何问题都没有给我任何答案。

在后台将字符串从活动传递到广播接收器的最佳方法是什么?

这是我的主要活动

public class AppActivity extends DroidGap {
 SmsReceiver mSmsReceiver = new SmsReceiver();

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     

    ScrollView scroll;
    scroll = new ScrollView(this);

    Bundle bundle = getIntent().getExtras();
    final String ownAddress  = bundle.getString("variable");

    registerReceiver(mSmsReceiver, new IntentFilter("MyReceiver"));
             Intent intent = new Intent("MyReceiver");
              intent.putExtra("passAddress", ownAddress);
             sendBroadcast(intent);

            Log.v("Example", "ownAddress: " + ownAddress);
 }
}


这是我的广播接收器

public class AppReceiver extends BroadcastReceiver {
 public void onReceive(Context context, Intent intent) {

    final String ownAddress  = intent.getStringExtra("passAddress");
    Toast test = Toast.makeText(context,""+ownAddress,Toast.LENGTH_LONG);
    test.show();

    Log.v("Example", "ownAddress: " + ownAddress);

 }
}


这是我的接收器的清单

<service android:name=".MyService" android:enabled="true"/>
 <receiver android:name="AppReceiver">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_SENT"/>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
 <receiver>
<service android:name=".MyServiceSentReceived" android:enabled="true"/>
 <receiver android:name="AppReceiver">
                <intent-filter android:priority="2147483645">
                    <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
 </receiver>

当广播接收器记录事件时,应用程序崩溃。我需要让它在幕后运行并从我的主要活动中拉出一个字符串。

任何人都可以帮我解决这个问题,还是指出我正确的方向?

1 个答案:

答案 0 :(得分:3)

添加评论和聊天

除非Intent在Bundle extras中有一个带有键ownAddress的String,否则您的String passAddress将始终为null。任何时候您的Receiver捕获一个Intent(无论是SMS_SENTSMS_RECEIVED还是BOOT_COMPLETEDownAddress都将为null,因为操作系统不提供名为{{1的字符串的额外字符串}}。希望能够解决问题。

原始答案

我没有使用DroidGap,但这是您想要的常规Android活动。

的活动:

passAddress

接收器:

public class AppActivity extends Activity {
    AppReceiver mAppReceiver = new AppReceiver();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        registerReceiver(mAppReceiver, new IntentFilter("MyReceiver"));

        String string = "Pass me.";
        Intent intent = new Intent("MyReceiver");
        intent.putExtra("string", string);
        sendBroadcast(intent);
    }
}   

不要忘记在onDestroy()中取消注册接收器,如下所示:

public class AppReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, intent.getStringExtra("string"), Toast.LENGTH_LONG).show();
    }
}