我只想获取数据并在吐司消息或通知消息上显示。所以我在主线程中创建了一个服务。(UI线程)我刚刚启动了一个新的线程来获取数据并将其放在Logs in Service中。代码:
public class HelloService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
MyThread th = new MyThread();
th.start();
try
{
th.join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return START_STICKY;
}
}
class MyThread extends Thread
{
public void run()
{
while(true)
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String response;
String dataToSend = "http://berkrevolution.com";
Log.i("FROM STATS SERVICE DoBackgroundTask", dataToSend);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(dataToSend);
try
{
httpPost.setEntity(new StringEntity(dataToSend, "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("Accept-Encoding", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null)
{
response = EntityUtils.toString(responseEntity);
Log.i("sonuc", response);
}
else
{
response = "{\"NO DATA:\"NO DATA\"}";
}
}
catch (ClientProtocolException e)
{
response = "{\"ERROR\":" + e.getMessage().toString() + "}";
} catch (IOException e) {
response = "{\"ERROR\":" + e.getMessage().toString() + "}";
}
}
}
}
但是20秒后我收到了一个错误。错误是:
11-22 13:30:44.831: A/libc(29854): Fatal signal 6 (SIGABRT) at 0x00000470 (code=0), thread 29854 (le.project1)
即使主程序关闭,我也需要提供全天候工作的服务。但是,我试图使用服务,我得到了这个错误。我该如何解决这个问题?
我如何在UI线程中启动服务:
public void startServ(View view)
{
//Toast.makeText(this, "Hey", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, HelloService.class);
startService(intent);
}