Java android HttpRequest每3秒通过服务一次
我只想获取数据并将其显示在toast消息或通知消息上。所以我在主线程(UI线程)中创建了一个服务,我刚刚启动了一个新线程来获取数据,并将其放在服务的日志中。代码:Java android HttpRequest每3秒通过服务一次,java,android,multithreading,http,service,Java,Android,Multithreading,Http,Service,我只想获取数据并将其显示在toast消息或通知消息上。所以我在主线程(UI线程)中创建了一个服务,我刚刚启动了一个新线程来获取数据,并将其放在服务的日志中。代码: public class HelloService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override publ
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)
我需要做一个服务,应该工作24/7,即使主程序关闭。但是,每当我尝试使用服务时,我都会遇到这个错误。我怎样才能解决这个问题
如何在UI线程中启动服务:
public void startServ(View view)
{
//Toast.makeText(this, "Hey", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, HelloService.class);
startService(intent);
}
这是一个非常糟糕的设计。这会耗尽手机的电池。最好使用GCM推送通知,并在收到通知时在
IntentService
内运行HTTP请求。通过这种方式,您可以友好地使用电池并保持数据的最新状态。GCM高优先级消息也可以绕过Android 6睡眠模式,因此您也不必担心。如果我关闭主程序,IntentService将关闭:)这就是GCM的全部要点。您的服务不应无限期地运行并发出HTTP请求。当您在BroadcastReceiver中发送推送通知时,您可以启动一个新的wakeful IntentService。即使我尝试使用GCM,它也应该使httppost投入服务。所以我的问题是,当我在服务中尝试httppost时,我的程序由于给定的错误而崩溃。当Android认为UI挂起时,就会发生这种情况<代码>服务在主UI线程上运行,因此可能导致该错误IntentService
在它们自己的线程上运行,因此不会导致此问题。