失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > android 获取nfc Android:在服务类中读取NFC标签

android 获取nfc Android:在服务类中读取NFC标签

时间:2021-07-29 01:13:27

相关推荐

android 获取nfc Android:在服务类中读取NFC标签

我正在开发一个应用程序,我需要读取存储在NFC标签中的数据,通过数据我的意思是简单的整数值,如0,1,2,3等。 从NFC读取数据的function在Activity类中工作正常但我需要在后台运行应用程序,所以即使应用程序没有在前台运行,我也可以从NFC读取数据。 所以我写了一个服务类,并将函数从Activity移动到服务类。 但它没有用。

这是“MainActivity.java”protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startService(new Intent(this, MyService.class)); }

startService(new Intent(this,MyService.class));

此行启动服务类。

Service类是“MyService.java”

public class MyService extends Service { private NfcAdapter mNfcAdapter; private PendingIntent mNfcPendingIntent; private IntentFilter[] mReadTagFilters; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP), 0); IntentFilter ndefDetected = new IntentFilter( NfcAdapter.ACTION_NDEF_DISCOVERED); ndefDetected.addDataScheme("http"); IntentFilter techDetected = new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED); mReadTagFilters = new IntentFilter[] { ndefDetected, techDetected }; Log.v("service", "return from onCreate function"); } @Override public void onDestroy() { super.onDestroy(); } @Override @Deprecated public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.v("service", "onStart function"); if (mNfcAdapter != null) { if (!mNfcAdapter.isEnabled()) { new AlertDialog.Builder(this) .setTitle("NFC Dialog") .setMessage("Please switch on NFC") .setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { Intent setnfc = new Intent( Settings.ACTION_WIRELESS_SETTINGS); startActivity(setnfc); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { dialog.dismiss(); } }).create().show(); } mNfcAdapter.enableForegroundDispatch (MainActivity.mContext, mNfcPendingIntent, mReadTagFilters, null); } else { Toast.makeText(this, "Sorry, NFC adapter not available on your device.", Toast.LENGTH_SHORT).show(); } Log.v("service", "return fonStart function"); } }

在这个onCreate()函数运行正常。 问题是这一行:

mNfcAdapter.enableForegroundDispatch (mContext, mNfcPendingIntent, mReadTagFilters, null);

函数的第一个参数接受Activity的上下文,这就是我被困住的地方。 有没有办法解决这个或任何替代方案。 感谢您的帮助。

Android的NFCfunction(特别是接收标签,Beam等的Intents)仅适用于前台活动。

如果觉得《android 获取nfc Android:在服务类中读取NFC标签》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。