私はNFCタグに格納されたデータを読む必要があるアプリケーションで作業しています。データは単純な整数値で、0,1,2,3などです。 NFCからデータを読み取る関数は、Activityクラスにあるときに正常に動作しますが、バックグラウンドでアプリケーションを実行する必要があります。アプリケーションがフォアグラウンドで実行されていなくても、NFCからデータを読み取ることができます。だから、私はサービスクラスを書いて、そのアクティビティをサービスクラスに移しました。しかし、それは動作しませんでした。
Android:サービスクラスのNFCタグを読む
これは、 "MainActivity.java"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
}
STARTSERVICE(新しいインテント(この、MyService.class))です。
この行は、サービスクラスを開始します。
サービスクラスは、この中でのonCreate()機能がうまく動作している "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");
}
}
です。問題は、この行です:
mNfcAdapter.enableForegroundDispatch (mContext, mNfcPendingIntent,
mReadTagFilters, null);
関数の最初の引数は、活動の状況を受け入れ、私は立ち往生午前場所です。 これまたは他の方法を解決する方法はありますか?ご協力ありがとうございました。
返信いただきありがとうございますが、デフォルトのアンドロイドNFCがバックグラウンドで実行中にタグを読み取り、ブラウザでデータを開こうとする方法をお勧めしますか? –
NFCタグ検出は、NFCシステムサービスによって処理されます。システムサービスは、インテントに基づいて**アクティビティ**を通知します。 Webブラウザは、NFCイベントを受信する他のアクティビティと同様に、それらのインテントに対してインテントフィルタが登録されています。 –