manhon
manhon

Reputation: 683

android, how to keep a thread running in service?

I have created an app. It starts a service(onStartCommand type). It creates a thread that keeps on monitor the clipboard:

private class MonitorTask extends Thread {
    @Override
    public void run() {
        mKeepRunning = true;
        while (true) {
            doTask(); //-this function uses the toast to show the string in clipboard
            try {
                Thread.sleep(300);
            } catch (InterruptedException ignored) {
            }
            if (!mKeepRunning) {
                break;
            }
        }
    }

I found that the after some time passed, the service was still there (according to running service manager), but the thread disappeared. How can I keep the thread running forever until user closes the app.

I guess that may be InterruptedException, how can I use that catch to restart the Thread?

Some old threads mentioned using AlarmManager to "startup the service and do something, close the service" at regular interval, but i dont think it is a good idea?

Please let me know if there is a typical way to do so or any good idea? thanks in advance.

Update in fact, i know there is ClipboardManager, but i know this one is not compatible to android 2.3.4. Besides, I would like to know if I want to create a thread in service, how can i reset it if it was killed? thanks

Upvotes: 0

Views: 1044

Answers (2)

Martin Cazares
Martin Cazares

Reputation: 13705

The best way to accomplish what you are trying to do is by using the ClipboardManager class, always try to avoid doing you own "Monitoring" functionality specially when it already exist in the OS and make sure if the OS itself already provides a BroadcastReceiver triggering an action with whatever you are expecting, take a look at the documentation for this class:

http://developer.android.com/reference/android/content/ClipboardManager.html

Instead of having a thread running doing nothing, draining battery and performance, why dont you create a BroadcastReceiver waitting for Clipboard actions, make use of the method:

ClipboardManager.addPrimaryClipChangedListener(ClipboardManager.OnPrimaryClipChangedListener what)

to be notified of any changes...

Regards!

Upvotes: 1

Tushar Pandey
Tushar Pandey

Reputation: 4857

inside this : http://developer.android.com/guide/components/services.html , Extending the Service class will help you !

Upvotes: 0

Related Questions