我如何在Android上的后台线程上运行代码?

我想要一些代码不断在后台运行。 我不想在服务中做到这一点。 有没有其他的方法可行?

我已经尝试在我的Activity调用Thread类,但是我的Activity在某个时间保持在后台,然后停止。 Thread类也停止工作。

 class testThread implements Runnable { @Override public void run() { File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt"); int i=0; RandomAccessFile in = null; try { in = new RandomAccessFile(file, "rw"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //String line =null; while (true) { HttpEntity entity=null; try { if (isInternetOn()) { while ((line = in.readLine()) != null) { HttpClient client = new DefaultHttpClient(); String url = "some url"; HttpPost request = new HttpPost(url); StringEntity se = new StringEntity(line); se.setContentEncoding("UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); entity = se; request.setEntity(entity); HttpResponse response = client.execute(request); entity = response.getEntity(); i++; } if((line = in.readLine()) == null && entity!=null) { file.delete(); testThread t = new testThread(); Thread t1 = new Thread(t); t1.start(); } }// end of if else { Thread.sleep(60000); } // end of else }// end of try catch (NullPointerException e1) { e1.printStackTrace(); } catch (InterruptedException e2) { e2.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }// end of while }// end of run 

如果你需要:

  1. 在后台线程上执行代码

  2. 执行不会触摸/更新用户界面的代码

  3. 执行(短)代码将花费最多几秒钟完成

那么请使用以下干净高效的使用AsyncTask的模式:

 AsyncTask.execute(new Runnable() { @Override public void run() { //TODO your background code } }); 

对于长期的后台进程,线程对于Android来说并不是最佳的。 但是,这里的代码,并自行承担风险…

记住服务或线程将在后台运行,但我们的任务需要做出触发(一次又一次调用)来获取更新,即一旦任务完成,我们需要调用下一次更新的function。

定时器(定时触发),闹钟(时基触发),广播(事件基本触发),recursion唤醒我们的function。

 public static boolean isRecursionEnable = false; void runInBackground() { if (isRecursionEnable) return; // Handle not to start multiple parallel threads isRecursionEnable = true; // on exception on thread make it true again new Thread(new Runnable() { @Override public void run() { // DO your work here // get the data if (activity_is_not_in_background) { runOnUiThread(new Runnable() { @Override public void run() { //uddate UI runInBackground(); } }); } else { runInBackground(); } } }).start(); } 

我想要一些代码不断在后台运行。 我不想在服务中做到这一点。 有没有其他的方法可行?

AsyncTask很可能是您正在寻找的机制。 它直接指定在后台线程上执行后台进程。 另外它的主要好处是提供了一些在Main(UI)线程上运行的方法,并且如果你想让用户了解一些任务进度或者用后台进程检索的数据更新UI,就可以更新你的UI。

如果你不知道如何从这里开始是很好的教程:

  • 了解AsyncTask – 一劳永逸

注意:也有可能与ResultReceiver一起使用IntentService

AsyncTask的替代方法是robospice。 https://github.com/octo-online/robospice

一些robospice的function。

1.asynchronous执行(在后台的AndroidService)networking请求(例如:使用Spring Android的REST请求)。当结果准备就绪时,在UI线程上通知应用程序。

2.强烈键入! 您使用POJO提出请求,并根据请求结果获得POJO。

3.不要在用于请求的POJO上,也不要在您的项目中使用的Activity类上施加任何限制。

4.caching结果(在Json中使用Jackson和Gson,或者Xml,或者纯文本文件或者二进制文件,甚至使用ORM Lite)。

5.只有在networking请求仍然存在的情况下,才告知你的活动(或任何其他情况)

6.不像Android的AsyncTasks通知你的活动在他们的UI线程上,就像Android Loaders一样,没有内存泄漏。

7.使用简单但强大的exception处理模型。

样品开始。 https://github.com/octo-online/RoboSpice-samples

https://play.google.com/store/apps/details?id=com.octo.android.robospice.motivations&feature=search_result上的robospice示例。;