【发布时间】:2015-06-17 13:49:35
【问题描述】:
我正在尝试使用 HttpGet 发送值。该功能位于服务中。我正在尝试的是,当我单击 Activity 发送此值的按钮时,以及当我的应用程序结束时。当应用程序打开时它工作正常,我可以发送值并使用 Toast 消息查看此值。当我结束应用程序时我可以在 Toast 中看到值,但是当检查时我发现它们没有转到网页,然后是我的数据库。我的代码如下,
public class LocService extends Service {
Timer timer;
Handler handler;
Location location1;
String logId = "";
final static long TIME= 10000;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location loc) {
location1 = new Location(loc);
tempVeriler.loc = new Location(loc);//tempVeriler is a class keeps temp values
}
};
boolean gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (tempVeriler.id != null)
logId = tempVeriler.id;
if (gps_enabled) {
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locListener);
} else if (network_enabled) {
locManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
timer= new Timer();
handler = new Handler(Looper.getMainLooper());
timer.schedule(new TimerTask() {
@Override
public void run() {
giveInfo();
}
}, 0, TIME);
}
private void giveInfo() {
handler.post(new Runnable() {
@Override
public void run() {
if (location1 != null) {
getInternetData();
Toast.makeText(
LocService.this,
location1.getLatitude() + " "
+ location1.getLongitude(),
Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
public void getInternetData() {
HttpClient client = new DefaultHttpClient();
URI website;
try {
website = new URI(
"http://www.someadress.com/Default.aspx?logID="
+ logID+ "&latitude="
+ new Double(location1.getLatitude()).toString()
+ "&longitude="
+ new Double(location1.getLongitude()).toString());
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
} catch (Exception e) {
}
}
【问题讨论】:
-
很抱歉,它必须是 handler
-
什么是?处理程序使用主/UI 线程循环器...所有可运行文件发布到此处理程序在主/UI 线程上运行...又一个 NetworkOnMainThreadException 问题...您为什么要使用处理程序? ...如果你像
catch (Exception e) { }那样吞下它,你也永远不会得到例外 -
异常的名称是 NetworkOn Main ThreadException 不是 NetworkOnUIThreadException
-
我不知道为什么,但只有计时器它会停止应用程序所以我发现如果你有任何其他建议或链接会很棒:)
-
什么是你的 onlocationchanged 方法在你的 timertask 之前执行的保证。在这种情况下,location1 对象上可能存在空指针异常。所以最好在调用 onlocationchanged 后触发定时器任务。
标签: android background android-service http-get