由于互联网连接不良,intentservice崩溃了

时间:2015-10-29 07:20:12

标签: android http-post android-intentservice

我正在尝试通过意向服务中的POST方法发送数据。但是,如果数据连接(互联网)不好,应用程序崩溃。我被建议使用线程而不是intentservice becuz线程可以通过POST方法处理多个实例,但intentservice不能。如果我应该完全使用线程而不是IntentService,或者在IntentService中尝试使用POST方法的线程,请建议。提前致谢。附:我有一个时间任务,在我的MainActivity中启动IntentService,每2分钟启动一次服务。

package com.example.anew;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ParseException;

public class LocalService extends IntentService{
	
	String Sender, TimeStamp, Mesg, webResponse, value;
    SQLiteDatabase db;
    public static final String PREFS_NAME = "MyApp_Settings";

	public LocalService() {
		super("LocalService");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
		 Cursor c=db.rawQuery("SELECT * FROM student", null);
		  if(c.getCount()==0){
			  System.out.println("No SMS found");
              return;
		  }
		
		  else if(c.moveToFirst()){
	          for(int i=0;i<c.getCount();i++){             
	              Sender = c.getString(1);
	              TimeStamp = c.getString(2);
	              Mesg = c.getString(3); 
	              readWebPage(c.getString(0));  //POST method
	              c.moveToNext();                 
	          }           

	      }

		  c.close();
	}

	private void readWebPage(String id) {
		// TODO Auto-generated method stub
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		value = settings.getString("code", "");
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://example.com/mail.asmx/send?"); 

		//Post Data
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
		nameValuePair.add(new BasicNameValuePair("id", value));
		nameValuePair.add(new BasicNameValuePair("type", "IN"));
		nameValuePair.add(new BasicNameValuePair("source", Sender));
		nameValuePair.add(new BasicNameValuePair("time", TimeStamp));
		nameValuePair.add(new BasicNameValuePair("body", Mesg));

		//Encoding POST data
		try{
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		}catch (UnsupportedEncodingException e) {

			e.printStackTrace();
			System.out.println(e);
		}

		//making POST request.
		try{
			HttpResponse response = httpClient.execute(httpPost);
			String XmlString = EntityUtils.toString(response.getEntity());
			XmlString=XmlString.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
			XmlString = XmlString.substring(XmlString.indexOf("[") + 1, XmlString.lastIndexOf("]"));
			JSONObject jObj = new JSONObject(XmlString);
			webResponse = jObj.getString("status");
            System.out.println("Web Response:" + webResponse);
            
            if(webResponse.equals("ok")){
            	
          if(id!=null){
        			
                    db.execSQL("DELETE FROM student WHERE id="+id);
          }
          else{
            		
                    System.out.println("No SMS found");
          }
            	
        
            	
            }


		}catch (ClientProtocolException e) {
		// Log exception
		e.printStackTrace();
		System.out.println(e);
		} catch (IOException e) {
		// Log exception
		e.printStackTrace();
		System.out.println(e);
		} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		System.out.println(e);
		} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}

		
	} // readWebPage ends
	
}

1 个答案:

答案 0 :(得分:0)

我建议您使用AsyncTask将数据发送到服务器,如果失败则重复或重新安排(如果需要)。 这里有一个示例(我复制了您的代码,但尚未对其进行测试,但它仍然有用):https://gist.github.com/jacktech24/71a28047a8007cab1c50

此外,如果您需要在一段时间后做一些网络工作,最好使用GcmNetworkManagers OneOffTask(如果您在目标设备上提供Google Play服务,如果您的应用程序是从Play商店安装的,则为真),您可以找到这里有一个例子https://github.com/jacktech24/gcmnetworkmanager-android-example