I am tryin to send values with HttpGet. The function is in a Service. What i'm trying is when i'm click the button from Activity sending this values,and when my app is ended.It's working fine when app is open i can sending values and see this values with Toast message.When i end app just i can see values in Toast,but when check i see they didn't go to Web Page and then my database.My code follows,
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) {
}
}
You can not perform any networking task in UI or Main thread, you have to use handler for that purpose. Change your getInternetData() method in this way,
And please read this NetworkOnMainThreadException | Android Developers