我想要一些代碼在後臺連續運行。我不想在服務中做到這一點。有沒有其他方法可行?如何在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
嗨。你可以請張貼一些代碼作爲你嘗試過的例子嗎?在後臺線程上運行代碼有不同的方法,但是您必須記住,如果您訪問的是任何UI組件,則必須使用'runOnUiThread()'方法在UI線程上訪問它們。 – 2013-03-18 08:28:16
是否有任何特別的原因,不使用服務 – DeltaCap 2013-03-18 08:29:49
這是不推薦。連續運行會排出設備電池。 – HelmiB 2013-03-18 08:32:28