public class MyService extends BackgroundService implements LocationListener {
private final static String TAG = MyService.class.getSimpleName();
private String mHelloTo = "World";
private LocationManager locationManager;
boolean ineternetAvailable = false;
private String provider;
Context context;
int bat_level = 0;
GPSTracker gps;
String username;
CommentsDataSource datasource;
NetworkConnectivityListener nw;
@Override
public void onCreate() {
context = getApplicationContext();
datasource = new CommentsDataSource(context);
gps = new GPSTracker(context);
datasource.open();
mHelloTo = datasource.getComment_1();
nw = new NetworkConnectivityListener();
}
@Override
protected JSONObject doWork() {
// ConnectionDetector cd = new ConnectionDetector(context);
**JSONObject result = new JSONObject();
try {
nw.startListening(context);
context.registerReceiver(this.batteryInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = 0;
String msg = "KAsun " + mHelloTo + " - its currently "
+ gps.getLongitude();
result.put("Message", msg);
Log.i("Networ", nw.getState().toString());
if (nw.getState().toString().equals("CONNECTED")) {
sendPostRequest("" + gps.getLongitude(),
"" + gps.getLatitude(), this.mHelloTo, "" + bat_level);
}
else {
Handler h = new Handler(context.getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context,
"Internet Connection is Not Available",
Toast.LENGTH_LONG).show();
}
});
}
Log.d(TAG, msg);
datasource.close();**
} catch (JSONException e) {
}
return result;
}
@Override
protected JSONObject getConfig() {
JSONObject result = new JSONObject();
try {
result.put("HelloTo", this.mHelloTo);
} catch (JSONException e) {
}
return result;
}
@Override
protected void setConfig(JSONObject config) {
try {
if (config.has("HelloTo"))
this.mHelloTo = config.getString("HelloTo");
} catch (JSONException e) {
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
bat_level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
}
};
private void sendPostRequest(String lo, String la, String username,
String batlevel) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String lo = params[0];
String la = params[1];
String username = params[2];
String b_level = params[3];
System.out.println("*** doInBackground ** paramUsername " + lo
+ " paramPassword :" + la + "Username" + username
+ "BatLevel" + b_level);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
// Therefore we use only the web page URL as the parameter of
// the HttpPost argument
HttpPost httpPost = new HttpPost(
"http://gateway.ceylonlinux.com/Ceylon_Steel/service/markGPSLocation");
BasicNameValuePair longtiude = new BasicNameValuePair(
"latitude", lo);
BasicNameValuePair lattiude = new BasicNameValuePair(
"longitude", la);
BasicNameValuePair username_param = new BasicNameValuePair(
"userName", username);
BasicNameValuePair batery_level = new BasicNameValuePair(
"batteryLevel", b_level);
// We add the content that we want to pass with the POST request
// to as name-value pairs
// Now we put those sending details to an ArrayList with type
// safe of NameValuePair
List<BasicNameValuePair> nameValuePairList = new ArrayList();
nameValuePairList.add(longtiude);
nameValuePairList.add(lattiude);
nameValuePairList.add(username_param);
nameValuePairList.add(batery_level);
try {
// UrlEncodedFormEntity is an entity composed of a list of
// url-encoded pairs.
// This is typically useful while sending an HTTP POST
// request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairList);
// setEntity() hands the entity (here it is
// urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient
.execute(httpPost);
// According to the JAVA API, InputStream constructor do
// nothing.
// So we can't initialize InputStream although it is not
// an interface
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("First Exception caz of HttpResponese :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second Exception caz of HttpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out
.println("An Exception given because of U rlEncodedFormEntity argument :"
+ uee);
uee.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("Result", result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(lo, la, username, batlevel);
}
}
以上代码作为后台服务工作,以获取当前的gps cordinetes并在每10秒内将其发送到服务器。在数据发送到服务器程序之前,它自我检查天气可以通过广播服务获得互联网连接。工作正常(如果互联网连接可用,它会发送已连接,如果没有发送 DISCONNECTED )。但如果我在数据发送时关闭互联网连接,应用程序将崩溃。< / p>
02-15 10:41:40.460: W/System.err(10109): java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
02-15 10:41:40.468: W/System.err(10109): at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:552)
02-15 10:41:40.476: W/System.err(10109): at libcore.io.IoBridge.recvfrom(IoBridge.java:516)
02-15 10:41:40.500: W/System.err(10109): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
02-15 10:41:40.507: W/System.err(10109): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
02-15 10:41:40.515: W/System.err(10109): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
答案 0 :(得分:1)
catch (ClientProtocolException cpe) {
System.out
.println("First Exception caz of HttpResponese :"
+ cpe);
cpe.printStackTrace();
}
catch (SocketTimeoutException s) {
} catch (HttpHostConnectException e) {
// TODO: handle exception
} catch (SocketException e) {
// TODO: handle exception
}
我应该添加上述异常来处理错误