读取NFC数据时的计时器

时间:2019-06-30 14:46:48

标签: java android

我正在做一个项目,以了解NFC数据可以从标签读取并显示在文本视图中的速度。当智能卡检测到TIMER将开始时,我会触发。这是我想要的问题,当数据(来自标签)在TEXTVIEW(tvNFCContent)中显示时,计时器将停止。

我将TextWatchter与OnTextChanged一起使用。但是不知何故计时器仍在运行,有人知道为什么吗?我需要停下来。

这是我的代码:

package com.asetmanajemennfc;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;



import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Read extends Activity {


    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[]; 
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low;


    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read);


        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);

        handler = new Handler() ;


     /*** Inisialisasi Variabel ***/
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};




// Coba Hapus tagDetected //


    mAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mAdapter == null) {
        // Stop here, we definitely need NFC
        Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
        finish();
    }

    readFromIntent(getIntent());

    }


     /******************************************************************************
     **********************************Read From NFC Tag***************************
     ******************************************************************************/
    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                   //udah coba//

                }
            }

            //udah coba//

            buildTagViews(msgs);
        }



}






    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);


        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }


     tvNFCContent.setText("NFC Content: " + text);


    tvNFCContent.addTextChangedListener(new TextWatcher() {

       @Override
        public void onTextChanged(CharSequence s, int start, int before,
        int count) {


        }

       @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
        }

       @Override
        public void afterTextChanged(Editable s) {


           TimeBuff += MillisecondTime;

             handler.removeCallbacks(runnable);

        }

    });    


    }  












    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }





    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub


        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {           
            Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();


              StartTime = SystemClock.uptimeMillis();
              handler.postDelayed(runnable, 0);



            NdefMessage[] messages = getNdefMessage(intent);            
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"Data di dalam kartu kosong",Toast.LENGTH_SHORT).show();
                return;
            }           
            byte[] payload = messages[0].getRecords()[0].getPayload();          
            userData = new String(payload);         

        }else
        {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }
    }





    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);

    }







    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;

            UpdateTime = TimeBuff + MillisecondTime;

            Seconds = (int) (UpdateTime / 1000);

            Minutes = Seconds / 60;

            Seconds = Seconds % 60;

            MilliSeconds = (int) (UpdateTime % 1000);

            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };







}

0 个答案:

没有答案