Android всплывает "новый тег обнаружен" вместо того, чтобы оставаться в моем приложении - PullRequest
0 голосов
/ 13 марта 2019

Когда я сканирую тег из моего приложения, открывается новая страница по умолчанию из Android вместо того, чтобы оставаться на странице моего приложения и разрешать мне читать содержимое.В частности, страница с надписью "Обнаружен новый тег и отображается его содержимое.

Это мое AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.lorcalhost.wakey">

    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />
    <uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
                  android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>

        </activity>
    </application>

</manifest>

И это мое MainActivity.kt:

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.nfc.NdefMessage
import android.nfc.NfcAdapter
import android.nfc.NfcManager
import android.os.Bundle
import android.provider.Settings
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity(), SensorEventListener {

    private var sensor: Sensor? = null
    private var sensorManager: SensorManager? = null
    private var nfcAdapter : NfcAdapter? = null
    private var nfcPendingIntent: PendingIntent? = null
    private var isRunning = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        checkNFCStatus()

        nfcPendingIntent = PendingIntent.getActivity(this, 0,
            Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)

        if (intent != null) {
            processIntent(intent)
        }


        myBackground.setBackgroundColor(Color.rgb(200,224,236))
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        hideStatusBar()

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_LIGHT)

        val actionBar = supportActionBar
        actionBar?.hide()

        btnNFCsettings.setOnClickListener {
            showNFCSettings()
            NFCstatus.visibility = View.INVISIBLE
            btnNFCsettings.visibility = View.INVISIBLE

        }

    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {

    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (event!!.values[0] < 10 && isRunning == false){
            isRunning = false
            myBackground.setBackgroundColor(Color.rgb(0,0,0))
            NFCsupport.setTextColor(Color.rgb(255, 255, 255))
            NFCstatus.setTextColor(Color.rgb(255, 255, 255))
        }
        else {
            isRunning = false
            myBackground.setBackgroundColor(Color.rgb(200,224,236))
            NFCsupport.setTextColor(Color.rgb(0, 0, 0))
            NFCstatus.setTextColor(Color.rgb(0, 0, 0))
        }


    }

    override fun onResume() {
        super.onResume()
        nfcAdapter?.enableForegroundDispatch(this, nfcPendingIntent, null, null)
        sensorManager!!.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)

    }

    override fun onPause() {
        super.onPause()
        nfcAdapter?.disableForegroundDispatch(this)
        sensorManager!!.unregisterListener(this)
    }

    override fun onNewIntent(intent: Intent){
        setIntent(intent)
        if (intent != null) processIntent(intent)
    }

    private fun processIntent(checkIntent: Intent) {
        if (checkIntent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) {
            val rawMessages = checkIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
            if (rawMessages != null && rawMessages.isNotEmpty()) {
                val ndefMsg = rawMessages[0] as NdefMessage
                if (ndefMsg.records != null && ndefMsg.records.isNotEmpty()) {
                    val ndefRecord = ndefMsg.records[0]
                    if(ndefRecord.toUri().toString() == "bedroom"){
                        tv_messages.text = ndefRecord.toUri().toString()
                        //logMessage("Done", "recognized")
                    }
                    else {
                        //logMessage("Done", "not recognized")
                    }

                }
            }

        }
    }



    private fun checkNFCStatus(){
        val isNfcSupported: Boolean = nfcAdapter != null
        if (isNfcSupported) {
            NFCsupport.text = "Nfc is not supported on this device"
            Toast.makeText(this, "Nfc is not supported on this device", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            val manager = this.getSystemService(Context.NFC_SERVICE) as NfcManager
            val adapter = manager.defaultAdapter
            if (!(adapter != null && adapter.isEnabled)) {
                NFCstatus.visibility = View.VISIBLE
                btnNFCsettings.visibility = View.VISIBLE
            }
        }
    }

    private fun showNFCSettings() {
        Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show()
        val intent = Intent(Settings.ACTION_NFC_SETTINGS)
        startActivity(intent)
    }

    private fun hideStatusBar(){
        window.setFlags(AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT)
        window.decorView.systemUiVisibility = 3328
    }

}

Я не знаю, что не так с моей текущей конфигурацией, любая помощь с благодарностью.

...