我写了使用NFC读取储存在它的一些数据的应用程序。 我的应用程序使用的碎片和碎片不附带onNewIntent()方法。 因为,我读的数据与我单独的类,它处理NFC相关的操作来完成,我需要做的唯一的事情就是更新片段内TextView的。 然而,这也实现可以使用新的意图传递给片段。
这是我目前的执行,这使得使用的接口。 收到后新的意向和NFC相关的检查成功,我呼吁听众。 这是它承载片段FragmentActivity。
public class Main extends FragmentActivity implements
ActionBar.OnNavigationListener {
private Bundle myBalanceBundle;
private NFC nfcObj;
private NewBalanceListener newBlanceListener;
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
}
@Override
protected void onResume() {
getNFCState();
super.onResume();
}
private void getNFCState() {
//Other NFC related codes
else if (nfc_state == NFC.NFC_STATE_ENABLED){
readNFCTag();
}
}
private void readNFCTag() {
//Other NFC related codes
if (getIntent().getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
nfcObj.setTag((Tag) getIntent().getParcelableExtra(
NfcAdapter.EXTRA_TAG));
nfcObj.readQuickBalance();
transitQuickReadFragment(nfcObj.getCurrentBalance());
}
}
private void transitQuickReadFragment(String balance) {
// Creates a balance bundle and calls to select MyBalance Fragment if it
// is not visible. Calls listener is it is already visible.
if (actionBar.getSelectedNavigationIndex() != 1) {
if (myBalanceBundle == null)
myBalanceBundle = new Bundle();
myBalanceBundle.putString(Keys.BALANCE.toString(), balance);
actionBar.setSelectedNavigationItem(1);
} else {
newBlanceListener.onNewBalanceRead(balance);
}
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
// Other fragment related codes
fragment = new MyBalance();
fragment.setArguments(myBalanceBundle);
newBlanceListener = (NewBalanceListener) fragment;
// Other fragment related codes
}
// Interface callbacks. You can pass new Intent here if your application
// requires it.
public interface NewBalanceListener {
public void onNewBalanceRead(String newBalance);
}
}
这是应查看mybalance片段,其具有的TextView需要每当NFC读取进行更新:
public class MyBalance extends Fragment implements NewBalanceListener {
private TextView mybalance_value;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Other onCreateView related code
Bundle bundle = this.getArguments();
if (bundle != null)
mybalance_value.setText(bundle.getString(Keys.BALANCE.toString(),
"0.00"));
else
mybalance_value.setText("0.00");
//Other onCreateView related code
}
@Override
public void onNewBalanceRead(String newBalance) {
mybalance_value.setText(newBalance);
}
}
此代码工作完全像预期为我的应用程序,但是,我想知道是否有更好的方式来处理来自片段新意图是什么?