如何启动一个服务的新主题? [英] How to start a new Thread in a service?
问题描述
我开发一个Android应用程序,我做一些繁重的工作(从在线网页带来的数据和分析它存储在数据库)的服务。目前,它正在采取有关20+分钟,这个时候我的UI是卡住了。我在考虑使用一个线程服务,使我的用户界面不会被卡住,但它给错误。我现在用的是下面的code:
I am developing an Android app and I am doing some heavy work (bringing data from an online web page and parsing it to store in database) in a service. Currently, it is taking about 20+ mins and for this time my UI is stuck. I was thinking of using a thread in service so my UI doesn't get stuck but it is giving error. I am using the following code:
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
sleep(1000);
Toast.makeText(getBaseContext(), "Running Thread...", Toast.LENGTH_LONG).show();
}
} catch (InterruptedException e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
};
thread.start();
这个简单的code是给运行时错误。就算我取出while循环,它仍然无法正常工作。 请,任何一个可以告诉我什么错误,我做的。很显然,我从一本电子书直接复制此code。这是假设的工作,但它不是。
This simple code is giving run time error. Even If I take out the while loop, it is still not working. Please, can any one tell me what mistake I am doing. Apparently, I copied this code directly from an e-book. It is suppose to work but its not.
推荐答案
新线程的创建从Android的样本采取的示例(Android为8 \ SampleSyncAdapter的\ src \ COM \例如\机器人\ samplesync \客户端\ NetworkUtilities.java):
Example of new thread creation taken from Android samples (android-8\SampleSyncAdapter\src\com\example\android\samplesync\client\NetworkUtilities.java):
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
可运行
是包含您的网络运营了Runnable。
runnable
is the Runnable that contains your Network operations.
这篇关于如何启动一个服务的新主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!