标签:
public class MainActivity extends Activity {
private Button mButton;
private NfcAdapter mNFCAdapter = null;
private PendingIntent mPendingIntent = null;
private String mPackageName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.mybutton);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
checkNFCFunction();
initNFC();
}
//因为当前是singleTop模式,所以当重新靠近NFC标签设备的时候,不会走onCreate函数,会响应onNewIntent函数
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
if(null != mNFCAdapter) {
mNFCAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
if(null != mNFCAdapter) {
mNFCAdapter.disableForegroundDispatch(this);
}
}
private void initNFC() {
//mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
mFilters = new IntentFilter[] {ndefDetected};
mTechLists = new String[][]{
new String[]{Ndef.class.getName()},
new String[]{NdefFormatable.class.getName()}
};
}
private void checkNFCFunction() {
mNFCAdapter = NfcAdapter.getDefaultAdapter(this);
if(mNFCAdapter == null) {
Toast.makeText(this, "该设备不支持NFC功能", 3000).show();
}
else {
if(!mNFCAdapter.isEnabled()) {
AlertDialog dialog;
AlertDialog.Builder customBuilder = new AlertDialog.Builder(this);
customBuilder.setTitle("提示")
.setMessage("该设备的nfc功能为打开,是否跳转到设置界面打开NFC功能")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent setnfc = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivity(setnfc);
}
});
dialog = customBuilder.create();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/zhangkefan/p/5043323.html