如何在 Android 的后台线程上运行代码? [英] How can I run code on a background thread on Android?
问题描述
我想要一些代码在后台持续运行.我不想在服务中这样做.有没有其他可能的方法?
I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?
我曾尝试在我的 Activity
中调用 Thread
类,但我的 Activity
会在后台停留一段时间然后停止.Thread
类也停止工作.
I have tried calling the Thread
class in my Activity
but my Activity
remains in the background for sometime and then it stops. The Thread
class also stops working.
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();
}
} else {
Thread.sleep( 60000 );
} // end of else
} 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
}
推荐答案
如果您需要:
在后台线程上执行代码
execute code on a background Thread
执行不接触/更新 UI 的代码
execute code that DOES NOT touch/update the UI
执行(短)代码,最多需要几秒钟才能完成
execute (short) code which will take at most a few seconds to complete
然后使用以下使用 AsyncTask 的简洁高效的模式:
THEN use the following clean and efficient pattern which uses AsyncTask:
AsyncTask.execute(new Runnable() {
@Override
public void run() {
//TODO your background code
}
});
这篇关于如何在 Android 的后台线程上运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!