【问题标题】:intentservice crashes due to bad internet connectivity由于互联网连接不良,intentservice 崩溃
【发布时间】:2015-10-29 07:20:12
【问题描述】:

我正在尝试通过意图服务中的 POST 方法发送数据。但是如果数据连接(互联网)不好,应用程序就会崩溃。有人建议我使用线程而不是意图服务,因为线程可以在通过 POST 方法发送数据时处理多个实例,但意图服务不能。请建议我是否应该完全使用线程而不是 IntentService 或尝试 IntentService 中的 POST 方法的线程。提前致谢。附言我有一个 timertask 在我的 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
	
}

【问题讨论】:

    标签: android http-post android-intentservice


    【解决方案1】:

    我建议您使用 AsyncTask 将数据发送到服务器并在失败时重复或重新安排(如果您需要)。 这里有一个例子(我复制了你的代码,但还没有测试过,它仍然可以工作):https://gist.github.com/jacktech24/71a28047a8007cab1c50

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

    【讨论】:

    • 我听说 asynctask 有 5 个线程池之类的东西。假设我一次要发送5个以上的数据,网络不好的时候还能发送数据吗?
    • 一次 5 个数据是什么意思?调用 AsyncTask 5 次?
    • 我的意思是我的代码从数据库中检索行并通过 POST 发送。它检索数据直到数据库变空,然后发送。如果网络连接不好并且有超过 5 个数据,asynctask 可能不会发送所有数据,然后 intentservice 将关闭。会是这样吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多