gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:43 24 4
gpt4 key购买 nike

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

我不是要详细的解释,而是要更多的确认。如果我完全错了也没关系。我是来学习的。

如果我理解正确的话:1. 服务在后台运行(无 UI)。2. 从理论上讲,服务将永远运行直到它 self 终止(我在这里猜测很大)3. 即使主 Activity 不可见(甚至被销毁又如何?),服务仍将继续运行

这是我的编码问题。

我有我的服务设置和线程。一切都很好,但它只能工作一次。我需要它循环并继续检查。一旦完成 run(),我该如何告诉它再次 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 团队做出的为数不多的优秀设计决策之一。

编辑 我忘了解决您关于多线程的问题。您不想让线程多次执行其 run() 方法。实例化一个新线程或围绕您希望重复的 run 逻辑的内容放置一个 while 循环。

关于android - 帮助我学习如何正确使用服务和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6105010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com