在我的应用程序中,我正在使用Intentservice从服务器获取数据,并将获取的数据存储到本地sqlite db中.我正在使用5 IntentService来获取并填充五个表.每个意向服务的数据最多可包含300行.我该怎么办?
IntentService代码:
public class SendBpRecordServer extends IntentService { DbHelper dbHelper; public static final String TAG="BP Service"; public JsONObject finalData; public SendBpRecordServer() { super("BP"); dbHelper=new DbHelper(this); Log.i("In Constructor",TAG); } @OverrIDe protected voID onHandleIntent(Intent intent) { String recname=intent.getStringExtra("naMetag"); if (recname.equals("fetch")) { Log.i("Send Data","Yes"); fetchDatFromServer(); ResultReceiver resultReceiver=intent.getParcelableExtra("receiverTagBP"); Log.d("BP Reseult ",resultReceiver.toString()); Bundle bun= new Bundle(); bun.putBoolean("Process_Complete_bp",true); resultReceiver.send(2, bun); } else { Log.i("InsIDe Service PUT BP ","Yes"); dataCollected(); } } private voID fetchDatFromServer() { Response.Listener Listener=new Response.Listener<JsONObject>() { @OverrIDe public voID onResponse(JsONObject response) { Log.i("Json Array Response", response.toString()); try { Boolean responseStatusCondition=response.getBoolean("success"); if (responseStatusCondition) { JsONArray JsonArray=response.getJsONArray("response"); Log.i("Array Size is",Integer.toString(JsonArray.length())); for (int i=0;i<JsonArray.length();i++) { JsONObject childJsONObject = JsonArray.getJsONObject(i); //Set the flag bit to 1 since data is already at server long result=dbHelper.insertIntoBloodPressureDetails(childJsONObject.getInt("systolic"), childJsONObject.getInt("diastolic"), childJsONObject.getLong("timestamp"),1 ); // Log.i("Insertion result ",Long.toString(result)); } Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILliSECOND, 0); //This is mIDnight time in GMT long unixTimeStamp = c.getTimeInMillis(); //Convert it in to Indian time System long indianMIDNightTime=unixTimeStamp-19800000; //Log.i("Now Calculates Days","doing"); dbHelper.calculateDays(dbHelper.bptablename, dbHelper.bpColUMN_days, dbHelper.bpColUMN_timestamp, indianMIDNightTime); } }catch (JsONException Js) { Js.printstacktrace(); } } }; Response.ErrorListener errorListener=new Response.ErrorListener() { @OverrIDe public voID one rrorResponse(VolleyError error) { NetworkResponse response = error.networkResponse; // Handle Error if (error instanceof TimeoutError || error instanceof NoConnectionError) { error.printstacktrace(); Toast.makeText(getApplicationContext(), " this Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof AuthFailureError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show(); } else if (error instanceof ServerError && response != null) { try { String res = new String(response.data, httpheaderParser.parseCharset(response.headers, "utf-8")); // Now you can use any deserializer to make sense of data JsONObject obj = new JsONObject(); obj.put("New Error",res); Log.i("New Server Error",obj.toString()); } catch (UnsupportedEnCodingException e1) { // Couldn't properly decode data to string e1.printstacktrace(); } catch (JsONException e2) { // returned data is not JsONObject? e2.printstacktrace(); } } else if (error instanceof NetworkError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ParseError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show(); } else error.printstacktrace(); } }; String bp_url=Constants.url+"bp"; JsonObjectheader customrequest=new JsonObjectheader(bp_url, null, Listener, errorListener); RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(customrequest); } private voID dataCollected() { JsONArray JsonArray=new JsONArray(); ArrayList<Graph> arrayList=dbHelper.fetchDataFromBp(); for (int i=0;i<arrayList.size();i++) { Graph graph=new Graph(); graph=arrayList.get(i); try { JsONObject JsonObject=new JsONObject(); JsonObject.put("systolic",graph.getHeight()); JsonObject.put("diastolic",graph.getWeight()); JsonObject.put("timestamp",graph.getTime()); JsonArray.put(JsonObject); }catch (JsONException Js) { Js.printstacktrace(); } } finalData=new JsONObject(); try { finalData.put("bp",JsonArray); }catch (JsONException Js) { Js.printstacktrace(); } sendDatatoServer(); } private voID sendDatatoServer() { Response.Listener Listener=new Response.Listener<JsONObject>() { @OverrIDe public voID onResponse(JsONObject response) { try { // Parsing Json object response // response will be a Json object //Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show(); Boolean responseStatusCondition = response.getBoolean("success"); Log.i("Response BP",responseStatusCondition.toString()); if (responseStatusCondition) dbHelper.setTheFlagBptable(); else Log.i("Something Went Wrong"," On Server"); } catch (JsONException k) { Log.i("On Response",k.getMessage()); k.printstacktrace(); } } }; Response.ErrorListener errorListener=new Response.ErrorListener() { @OverrIDe public voID one rrorResponse(VolleyError error) { // Handle Error if (error instanceof TimeoutError || error instanceof NoConnectionError) { error.printstacktrace(); Toast.makeText(getApplicationContext(), " this Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof AuthFailureError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show(); } else if (error instanceof ServerError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show(); } else if (error instanceof NetworkError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); } else if (error instanceof ParseError) { //Todo error.printstacktrace(); Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show(); } else error.printstacktrace(); } }; Log.i("Bp Final Data",finalData.toString()); JsonObjectheader customrequest=new JsonObjectheader(Request.Method.PUT, Constants.url+"bp", finalData, Listener, errorListener); RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(customrequest); }}
调用intentservice的代码:
Log.i("Fetch BP Data ", SendBpRecordServer.TAG); resultReceiverBP=new MyResultReceiver(new Handler()); resultReceiverBP.setReceiver(this); Log.i("Bp resultreceiver ",resultReceiverBP.toString()); Intent intent2=new Intent(this,SendBpRecordServer.class); intent2.putExtra("naMetag","fetch"); intent2.putExtra("receiverTagBP",resultReceiverBP); startService(intent2);
并在完成任务时向我发送代码
在onReceiveResult ..中,结果代码通过调用的intentservice发送,并且当计数达到5时,启动mainactivity(尽管此技巧不起作用,即在未完成分配给intentservice的任务的情况下启动mainactivity).
@OverrIDe public voID onReceiveResult(int resultCode, Bundle resultData) { // Todo auto-generated method stub Log.d("Diabetes","received result from Service= "+resultData.getString("ServiceTag")); // Log.d("BMI ","received result from Service= "+resultData.getString("ServiceTag")); /* if (progressDialog.isShowing()) { progressDialog.dismiss(); }*/ Log.i("Get Values ",Integer.toString(Constants.getValues)); if (resultCode==0 && resultData.getBoolean("Process_Complete")) Constants.getValues++; if (resultCode==1 && resultData.getBoolean("Process_Complete_bmi")) Constants.getValues++; if (resultCode==2 && resultData.getBoolean("Process_Complete_bp")) Constants.getValues++; if (resultCode==3 && resultData.getBoolean("Process_Complete_med_stats")) Constants.getValues++; if (resultCode==4 && resultData.getBoolean("Process_Complete_one")) Constants.getValues++; if (Constants.getValues==5) { Constants.getValues=0; if (progressDialog.isShowing()) { progressDialog.dismiss(); } startActivity(new Intent(this,MainActivity.class)); finish(); } }
解决方法:
您是否绝对确定是UI冻结的根本原因是IntentService?意图服务是专门设计用于在工作线程中运行的,以便从主(UI)线程中卸载处理,其主要原因之一是有助于防止UI冻结.
也许尝试在UI级别开始调试工作.特别是,什么是在启动ResultReceiver时将其提供给IntentService的,以及在该接收者实例中的onReceiveResult回调方法中做什么?
除此之外,对于您遇到冻结的活动,请检查您正在执行哪种 *** 作.从主线程上的数据库中加载大量数据(即,不使用Loader或类似的方法将处理任务卸载到工作线程中)是导致UI冻结的常见原因,至少就目前为止我是这样.
更新
我想我已经解决了问题所在.有两个主要问题,都取决于您如何使用Volley.将请求添加到Volley队列时,该请求将异步执行.这意味着队列方法会立即返回.在您的意图服务代码中,这意味着该服务立即继续告诉ResultReceiver它已完成处理,而实际上它所完成的只是将请求排队.所有五个Intent服务都将执行此 *** 作,这意味着MainActivity将很快输入.这是第一个问题.
第二个问题说明了您遇到的冻结问题.尽管Volley在工作线程上执行请求,但它返回对主线程上的请求的已解析响应-请参阅文档here.这意味着您正在intent服务中进行的所有响应处理(将数据放入数据库等). )实际上发生在主(UI)线程上.这解释了冻结.
您在这里可能想要做的是改为使用Volley的RequestFuture.通过允许您阻止直到请求完成,这基本上将异步请求转换为同步请求.为此,请创建适当类型的Future(在您的情况下为JsONObject),并将其设置为请求的侦听器和错误侦听器.然后,像现在一样对请求进行排队,然后在以后立即调用get方法.该方法将阻塞,直到响应完成处理为止.可以在意图服务中执行此 *** 作,因为它在工作线程而不是UI线程上运行.
如果请求成功,您将获得返回的数据,并且可以执行Response.Listener实现中当前包含的所有逻辑.如果发生错误(即由于某种原因请求失败),将来的请求将引发异常,您可以处理该异常以采取任何适当的措施.
使用请求期货是与使用侦听器的完全不同的方法,您可能需要对代码进行一些更改才能使其正常工作,但是它应该可以解决您遇到的问题.
希望能对您有所帮助,我诚挚的歉意不提早发现此错误.
总结以上是内存溢出为你收集整理的java-IntentService冻结了我的应用程序用户界面全部内容,希望文章能够帮你解决java-IntentService冻结了我的应用程序用户界面所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)