我已经在我的 Activity 中实现了 NFC 前台调度。当我在Android 4.2.1设备(Samsung Galaxy Nexus)上运行时,代码运行良好。但是当我在Android 2.3.5设备 (HTC Desire S) 上运行时,会出现NullPointerException。这是我的活动的一些代码,onResume()
部分抛出异常:
public class MainActivity extends Activity{
private NfcAdapter mAdapter;
private IntentFilter[] intentFilterArray;
private PendingIntent pendingIntent;
private String[][] techArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
intentFilterArray = new IntentFilter[]{intentFilter};
techArray = new String[][]{new String[]{NdefFormatable.class.getName(), NfcA.class.getName()}};
}
@Override
protected void onResume(){
super.onResume();
//NullPointerException here,because mAdapter is Null, why?
mAdapter.enableForegroundDispatch(this, pendingIntent, intentFilterArray, techArray);
}
@Override
public void onPause() {
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
...
}
在Android 2.3.5设备上,(LogCat 向我展示)NullPointerException发生在onResume()
when call mAdapter.enableForegroundDispatch(…)
。我查了一下,是因为mAdapter
是null。为什么 ?