我正在尝试使用本地广播接收器在editText字段(在片段内)中显示扫描条形码。
这是我的代码:
MainActivity.java中的OnActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent){
Log.d("onActivityResultCalled", "yes");
if(requestCode == IntentIntegrator.REQUEST_CODE){
if (resultCode == RESULT_OK){
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Log.d("content", contents);
Log.d("format", format);
Log.d("sender", "Broadcasting message");
Intent scanIntent = new Intent("scanEvent");
scanIntent.putExtra("isbn",contents);
LocalBroadcastManager.getInstance(this).sendBroadcast(scanIntent);
}else if(resultCode == RESULT_CANCELED){
Log.e("MainActivity","Scan cancelled?");
}
}
}
接收广播和显示isbn的代码:
@Override
public void onResume()
{
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
new IntentFilter("scanEvent"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "scanEvent" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
isbnData = intent.getStringExtra("isbn");
Log.d("receiver", "Got message: " + isbnData);
isbn.setText(isbnData);
}
};
@Override
public void onPause() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
条形码本身的扫描成功。问题是能够在编辑文本中显示该条形码。
答案 0 :(得分:4)
您好像取消注册广播接收器了。
看一下有关onResume and onActivityResult的问题,onActivityResult
会在onResume
之前调用,所以当您的片段注册为接收者时,为时已晚。
尝试将广播接收者注册移至onCreate
和onDestroy
。