Frage

I am working on my school project, so i have a library file that is provided to me which scans a code from the card and returns it. The problem is it only works when i press a button. However, i want it to run always and when i scan a card, it will automaticly return the card id without pressing the button.

It gets the card value partially, card id is totally 16 characters but it takes 3-4 characters at a time. So it is like:

id=10 id=2310 id=632010 .... id = 123434233632010

And when there is no card, it returns null.

How can i create a asynctask that runs in background and scans infinitely? And when the code is 16 characters, it stops the task and starts a new activity?

Edit:

    public class TestService extends IntentService {

    public int handle, type = 0x26;
    MediaReader md = new MediaReader();
    String cardId;

    public TestService() {
        super("TestService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                cardId = "";
                int ret = md.CardPoll(type);
                if (ret == 0) {
                    for (int i = 0; i < md.uid_len; i++) {

                        cardId = cardId + md.uid[i];
                    }
                    Log.e("MyLogs", cardId);
                }
            } catch (NullPointerException e) {
                Log.e("deneme", "No card detected");
            }

        }

    }

}
War es hilfreich?

Lösung

An AsyncTask, despite to popular beliefs, is not intended to be run indefinitely and really shouldn't be. AsyncTask is meant to do short tasks that requires some effort or even network operations, and after, they just end.

If you're looking to run a loop indefinitely and you want to do it in background, I suggest using a background Service. This doesn't provide a Thread as AsyncTask's doInBackground() method does, but you can create one yourself.

As it is a Service, you'll need to handle it accordingly and always use startService() and stopService() when needed, otherwise even if your app is closed it might still be running when it's not needed (which is not a good practice).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top