android – 帮助我学习如何正确使用服务和线程

我正在寻求帮助,所以我的生活,更重要的是我的用户的生活不会因为我不知道如何正确使用服务和线程而毁掉.

我不是要求很长的解释,而是更多的确认.如果我错了,那就好了.我在这里学习.

如果我理解正确:
1.服务在后台运行(没有UI).
2.理论上服务将永远运行直到它自杀(我在这里做了一个很大的猜测)
3.即使主要活动不可见,服务也会继续运行(甚至毁坏了怎么样?)

所以这是我的编码问题.

我有我的服务设置和一个线程.一切都很好,但只能工作一次.我需要它循环并继续检查.一旦完成run(),我怎么去告诉它再次运行()?

public class NotifyService extends Service{

    private long mDoTask;

    NoteThread notethread;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        mDoTask = System.currentTimeMillis();
        notethread = new NoteThread();
        notethread.start(); 
    }


    public class NoteThread extends Thread {
        NotificationManager nManager;
        Notification myNote;

        @Override
        public synchronized void start() {
            super.start();
//init some stuff
        }

        @Override
        public void run() {
                    //If it's been x time since the last task, do it again
            //For testing set to every 15 seconds...
            if(mDoTask + 15000 < System.currentTimeMillis()){

//Take care of business
        mDoTask = System.currentTimeMillis();                   
            }
        }
    }
}

最佳答案 来自Android文档:

A Service is an application component
representing either an application’s
desire to perform a longer-running
operation while not interacting with
the user or to supply functionality
for other applications to use. Each
service class must have a
corresponding declaration in
its package’s AndroidManifest.xml.
Services can be started with
Context.startService() and
Context.bindService().

Note that services, like other
application objects, run in the main
thread of their hosting process. This
means that, if your service is going
to do any CPU intensive (such as MP3
playback) or blocking (such as
networking) operations, it should
spawn its own thread in which to do
that work. More information on this
can be found in Processes and Threads.
The IntentService class is available
as a standard implementation of
Service that has its own thread where
it schedules its work to be done.

You can find a detailed discussion
about how to create services in the
Services document.

换句话说,服务不会在后台运行,除非您将它放在一个线程中.如果您将一个永远不会在您的应用程序中结束的服务放在手动线程中,那么它将阻止.

Android提供了一个API来为您完成后台任务,而无需使用Java线程;它被称为AsyncTask,它是Android团队有史以来为数不多的GOOD设计决策之一.

编辑我忘了解决你关于多线程的问题.您不希望让一个线程多次执行其run()方法.要么实例化一个新线程,要么在你希望重复的运行逻辑的内容周围放置一个while循环.

点赞