广播接收错误

时间:2013-05-30 12:50:09

标签: android android-broadcast

情景:

我使用以下代码从片段发送广播

Intent intent=new Intent();
                    intent.setAction("writeBalanceToNFCCard");
                    intent.putExtra("balance", Double.valueOf(result));
                    getActivity().sendBroadcast(intent);

在MainActivity中,我收到了

private final BroadcastReceiver mReceiverWriteNFC=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        double newBalance = intent.getDoubleExtra("balance", 0);

        write(newBalance);
    }
};

在MainActivity的onCreate()中,我正在注册

 IntentFilter writeNFCFilter=new IntentFilter("writeBalanceToNFCCard");

   registerReceiver(mReceiverWriteNFC, writeNFCFilter);

问题: 它有时会工作.... enter image description here d有时会出现以下错误

我做错了什么???

编辑: 这是写方法

private void write(double newBalance) {
    Log.d(TAG, "Write to tag");

        //to display new balance on homefragment.
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
            editor.putString("newbalance",String.valueOf(newBalance));
            editor.commit();

            paymentData=new MyPaymentData();
        paymentData.setUid(operations.getUid());
        paymentData.setCurrency("dkk");
        paymentData.setAmount(newBalance);
        Log.d(TAG,"WRITE NFC: BALANCE="+ String.valueOf(newBalance));

        byte[] bytes = encodePayload(paymentData);
        byte[] encrypted = encrypt(bytes);

        new WriteTask().execute(encrypted,bytes);

}

编辑2:

错误之后,请参见下图,实际调用write()方法并执行其功能。问题是客户肯定不喜欢看到一个丑陋的应用程序崩溃消息.. !! enter image description here

2 个答案:

答案 0 :(得分:0)

您应该在onResume()方法中注册广播接收器,而不是onCreate()。并在onPause()方法中取消注册它们。我无法看到您的屏幕截图(在我的工作场所被屏蔽),但即使这不是当前的问题,也很快就会出现问题。

将寄存器接收器代码移动到onResume():

protected void onResume () {
    super.onResume();
    IntentFilter writeNFCFilter=new IntentFilter("writeBalanceToNFCCard");
    registerReceiver(mReceiverWriteNFC, writeNFCFilter);
}

onPause()应如下所示:

protected void onPause () {
    unregisterReceiver(mReceiverWriteNFC);
    super.onPause();
}

答案 1 :(得分:0)

问题似乎在这一行

paymentData.setUid(operations.getUid());

如果是,则唯一的原因是operations为空。请检查您是否正确初始化。