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 UrlEncodedFormEntity 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);
}
在这里,我编写了以上代码,以便在Android后台服务中向服务器发送一些数据.It 工作正常。但是当我从互联网上下来时,应用程序将崩溃。所有我想做的是防止应用程序在互联网不可用时崩溃。
01-02 11:46:57.437: I/System.out(10409): Second Exception caz of HttpResponse :org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.1:3128 refused
01-02 11:46:57.445: W/System.err(10409): org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.1:3128 refused
01-02 11:46:57.476: W/System.err(10409): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
01-02 11:46:57.484: W/System.err(10409): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-02 11:46:57.492: W/System.err(10409): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-02 11:46:57.492: W/System.err(10409): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-02 11:46:57.492: W/System.err(10409): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-02 11:46:57.492: W/System.err(10409): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-02 11:46:57.515: W/System.err(10409): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-02 11:46:57.523: W/System.err(10409): at org.apache.cordova.example.MyService$1SendPostReqAsyncTask.doInBackground(MyService.java:253)
01-02 11:46:57.523: W/System.err(10409): at org.apache.cordova.example.MyService$1SendPostReqAsyncTask.doInBackground(MyService.java:1)
01-02 11:46:57.539: W/System.err(10409): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-02 11:46:57.539: W/System.err(10409): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-02 11:46:57.539: W/System.err(10409): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-02 11:46:57.546: W/System.err(10409): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-02 11:46:57.546: W/System.err(10409): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-02 11:46:57.562: W/System.err(10409): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-02 11:46:57.679: W/System.err(10409): at java.lang.Thread.run(Thread.java:856)
01-02 11:46:57.703: W/System.err(10409): Caused by: java.net.ConnectException: failed to connect to /192.168.1.1 (port 3128): connect failed: ETIMEDOUT (Connection timed out)
01-02 11:46:57.734: W/System.err(10409): at libcore.io.IoBridge.connect(IoBridge.java:114)
01-02 11:46:57.796: W/System.err(10409): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-02 11:46:57.828: W/System.err(10409): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-02 11:46:57.875: W/System.err(10409): at java.net.Socket.connect(Socket.java:842)
01-02 11:46:57.875: W/System.err(10409): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-02 11:46:57.890: W/System.err(10409): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-02 11:46:57.953: W/System.err(10409): ... 15 more
01-02 11:46:57.953: W/System.err(10409): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
01-02 11:46:58.023: W/System.err(10409): at libcore.io.Posix.connect(Native Method)
01-02 11:46:58.031: W/System.err(10409): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
01-02 11:46:58.031: W/System.err(10409): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-02 11:46:58.039: W/System.err(10409): at libcore.io.IoBridge.connect(IoBridge.java:112)
01-02 11:46:58.039: W/System.err(10409): ... 20 more
01-02 11:46:58.039: D/AndroidRuntime(10409): Shutting down VM
01-02 11:46:58.039: W/dalvikvm(10409): threadid=1: thread exiting with uncaught exception (group=0x40f092a0)
01-02 11:46:58.062: E/AndroidRuntime(10409): FATAL EXCEPTION: main
01-02 11:46:58.062: E/AndroidRuntime(10409): java.lang.NullPointerException: println needs a message
01-02 11:46:58.062: E/AndroidRuntime(10409): at android.util.Log.println_native(Native Method)
01-02 11:46:58.062: E/AndroidRuntime(10409): at android.util.Log.i(Log.java:190)
01-02 11:46:58.062: E/AndroidRuntime(10409): at org.apache.cordova.example.MyService$1SendPostReqAsyncTask.onPostExecute(MyService.java:304)
01-02 11:46:58.062: E/AndroidRuntime(10409): at org.apache.cordova.example.MyService$1SendPostReqAsyncTask.onPostExecute(MyService.java:1)
01-02 11:46:58.062: E/AndroidRuntime(10409): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-02 11:46:58.062: E/AndroidRuntime(10409): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-02 11:46:58.062: E/AndroidRuntime(10409): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
答案 0 :(得分:3)
在开始AsyncTask
之前,请检查设备是否已启用网络连接
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
注意不要忘记在清单文件中添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:1)
请检查互联网连接并提供互联网连接权限
答案 2 :(得分:1)
使用以下方法检查互联网连接,尝试:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
还在清单文件中提供互联网权限和网络权限
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
使用以下方法:
if(isConnectingToInternet())
{
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(lo, la, username, batlevel);
}
else{
//Show alert to user for internet connection not available.
}
确保使用SendPostReqAsyncTask
数组传递params[]
方法中的参数。
String lo = params[0];
String la = params[1];
String username = params[2];
String b_level = params[3];
以上字符串是否获取值?尝试打印值。
答案 3 :(得分:0)
在开始网络操作之前检查。但此代码仅检查启动应用程序的时间。
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()){
//wifi is enabled
sendPostRequest(lo,la,username,batlevel);
}
else
{
Toast.makeText(context,"Please turn on the wifi...",5000);
}
如果在启动应用程序之前打开了wifi,这可能对您有用。但是如果用户在从服务器发送/接收数据时关闭了wifi,则可能会再次崩溃。 所以我认为你必须不断检查无线接入。请检查link以解决这个问题。
您需要的许可
<uses-permission android:name="android.permission.INTERNET"/>
<user-permission android:name="android.permission.ACCESS_WIFI_STATE" />