我想要一些代码在后台连续运行。我不想在服务中做到这一点。有没有其他方法可行?如何在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