Desidero che alcuni codici vengano eseguiti in background continuamente. Non voglio farlo in un servizio. C'è un altro modo possibile?Come posso eseguire il codice su un thread in background su Android?
Ho provato a chiamare la classe Thread
nel mio Activity
ma il mio Activity
rimane sullo sfondo per qualche tempo e poi si ferma. Anche la classe Thread
smette di funzionare.
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
Hi. Puoi per favore postare del codice come esempio di ciò che hai provato? Esistono diversi modi per eseguire il codice su un thread in background ma è necessario ricordare che se si accede a qualsiasi componente dell'interfaccia utente è necessario accedervi sul thread dell'interfaccia utente utilizzando il metodo 'runOnUiThread()'. –
C'è qualche ragione particolare per non utilizzare il servizio – DeltaCap
, ma non è consigliabile. il funzionamento continuo scaricherà la batteria del dispositivo. – HelmiB