应用程序关闭时,android volley不发送响应

时间:2015-01-15 10:52:32

标签: android android-volley

嗨已经创建了一个凌空程序,当我的应用程序运行时它工作正常...但是当应用程序关闭时,数据会发布到服务器但是它没有给出响应......来自服务器的代码是这样的方式...我已经把我所有的代码和这个运行在Intent服务所以请让我知道它出错的地方或者什么是凌空的问题

  public class CapitalService extends IntentService{
    NetworkInfo networkInfo;
    Intent mServiceIntent;
    Context context = this;
    public CapitalService(){
        super("Empty Constructor");     
    }
    public CapitalService(String name) {
        super(name);
    }
    @Override
    protected void onHandleIntent(Intent intent) {

        makeJsonObjectRequest();            
    }      
    private void makeJsonObjectRequest() {
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                "", obj, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            response.getString("success");

                            final NotificationManager mgr=
                                (NotificationManager)CapitalService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                            Notification note=new Notification(R.drawable.add_more,
                                                                            "Android Example Status message!",
                                                                            System.currentTimeMillis());

                            // This pending intent will open after notification click
                            PendingIntent i = PendingIntent.getActivity(CapitalService.this, 0,
                                                                    new Intent(CapitalService.this, Home.class),
                                                                    0);

                            note.setLatestEventInfo(CapitalService.this, "Android Example Notification Title",
                                                    "This is the android example notification message", i);

                            mgr.notify(2133, note);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(jsonObjReq);
    }


}

1 个答案:

答案 0 :(得分:1)

onHandleIntent 也是一个帖子,所以你可以把你的代码放在 onHandleIntent 中而不需要任何函数,所以你的代码应该如下所示:

public class CapitalService extends IntentService{
NetworkInfo networkInfo;
Intent mServiceIntent;
Context context = this;
public CapitalService(){
    super("Empty Constructor");     
}
public CapitalService(String name) {
    super(name);
}
@Override
protected void onHandleIntent(Intent intent) {

              JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            "", obj, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        response.getString("success");

                        final NotificationManager mgr=
                            (NotificationManager)CapitalService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                        Notification note=new Notification(R.drawable.add_more,
                                                                        "Android Example Status message!",
                                                                        System.currentTimeMillis());

                        // This pending intent will open after notification click
                        PendingIntent i = PendingIntent.getActivity(CapitalService.this, 0,
                                                                new Intent(CapitalService.this, Home.class),
                                                                0);

                        note.setLatestEventInfo(CapitalService.this, "Android Example Notification Title",
                                                "This is the android example notification message", i);

                        mgr.notify(2133, note);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
            0,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}      

}

或者你可以使用 asycktask 像这样:

    @Override
protected void onHandleIntent(Intent intent) {


        List<NameValuePair> params = new ArrayList<NameValuePair>();
        SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
        String user_id = prefs.getString("user_id", "");
        String last_1 = prefs.getString("last_id_general_news", "");
        String last_2=prefs.getString("last_id_local_news", "");
        String last_3=prefs.getString("last_id_events", "");
        String last_4=prefs.getString("last_id_gas", "");
        params.add(new BasicNameValuePair("user_id", user_id));
        params.add(new BasicNameValuePair("cat_1", last_1));
        params.add(new BasicNameValuePair("cat_2",last_2));
        params.add(new BasicNameValuePair("cat_3",last_3));
        params.add(new BasicNameValuePair("cat_4", last_4));


        JSONObject json = jParser.getJSONFromUrl(RestClient.URL_NOTIFICATION, params);

    try {
        JSONArray jsonArray = json.getJSONArray("request");
        int len = jsonArray.length();
        if (len > 0) {             
            for (int i = 0; i < len; i++) {

                JSONObject newsObj = jsonArray.getJSONObject(i);
                // if(!newsObj.toString().equals("{}")){

                if (newsObj.getString("news_category_id").equals("1")) {
                    NatureItemGeneralNews natureItemGeneralNews = new NatureItemGeneralNews();

                    natureItemGeneralNews.setId(Integer.valueOf(newsObj.getString("news_id")));
                    natureItemGeneralNews.setTitle(newsObj.getString("news_title"));
                    natureItemGeneralNews.setDate(newsObj.getString("news_updated_at"));
                    natureItemGeneralNews.setImgUrl(newsObj.getString("news_attachment"));
                    natureItemGeneralNews.setSubject(newsObj.getString("news_text"));
                    List<NatureItemGeneralNews> temp = new ArrayList<NatureItemGeneralNews>();

                    boolean exist=false;
                    for (NatureItemGeneralNews n : MainActivity.ListForGeneralNews) {
                        if(n.getId()==natureItemGeneralNews.getId()){
                            exist=true;
                        }
                    }
                    if(!exist) {
                        temp.add(natureItemGeneralNews);
                    }


                    for (NatureItemGeneralNews n : MainActivity.ListForGeneralNews) {
                        temp.add(n);

                    }
                    MainActivity.ListForGeneralNews = new ArrayList<>(temp);
                    MainActivity.LastIdGeneralNews = natureItemGeneralNews.getId();
                    Last_Id_General=natureItemGeneralNews.getId();

                    SharedPreferences prefs1 = getSharedPreferences("CommonPrefs", MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs1.edit();
                    editor.putString("last_id_general_news",natureItemGeneralNews.getId()+"");
                    editor.commit();


                    if(!exist) {
                        String ns = Context.NOTIFICATION_SERVICE;
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
                        int icon = R.mipmap.ic_lunch;
                        CharSequence tickerText = natureItemGeneralNews.getSubject();
                        long when = System.currentTimeMillis();

                        int requestID = (int) System.currentTimeMillis();
                        Notification notification = new Notification(icon, tickerText, when);
                        Context context = getApplicationContext();
                        Intent notificationIntent = new Intent(MyAlarmService.this, PageOfNew2.class);
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        notificationIntent.putExtra("news_id", natureItemGeneralNews.getId() + "");
                        notificationIntent.putExtra("news_title", natureItemGeneralNews.getTitle());

                        notificationIntent.putExtra("news_updated_at", natureItemGeneralNews.getDate());
                        notificationIntent.putExtra("news_attachment", natureItemGeneralNews.getImgUrl());
                        notificationIntent.putExtra("news_text", natureItemGeneralNews.getSubject());
                        notificationIntent.setAction("myString" + requestID);

                        PendingIntent contentIntent = PendingIntent.getActivity(MyAlarmService.this, requestID, notificationIntent, 0);
                        notificationIntent.setData((Uri.parse("mystring" + requestID)));
                        notification.setLatestEventInfo(context, natureItemGeneralNews.getTitle(), "", contentIntent);

                        notification.flags += Notification.FLAG_ONGOING_EVENT;
                        notification.flags += Notification.FLAG_AUTO_CANCEL;
                        Uri notification1 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification1);

                        r.play();
                        mNotificationManager.notify(NOT_ID_1, notification);
                    }

                } else if (newsObj.getString("news_category_id").equals("2")) {
                    NatureItemLocalNews natureItemLocalNews = new NatureItemLocalNews();
                    natureItemLocalNews.setId(Integer.valueOf(newsObj.getString("news_id")));
                    natureItemLocalNews.setTitle(newsObj.getString("news_title"));
                    natureItemLocalNews.setDate(newsObj.getString("news_updated_at"));
                    natureItemLocalNews.setImgUrl(newsObj.getString("news_attachment"));
                    natureItemLocalNews.setSubject(newsObj.getString("news_text"));
                    natureItemLocalNews.setCityName(Temp.getCityName(Integer.valueOf(newsObj.getString("news_city_id"))));
                    List<NatureItemLocalNews> temp = new ArrayList<NatureItemLocalNews>();


                    boolean exist=false;
                    for (NatureItemLocalNews n : MainActivity.ListForLocalNews) {
                        if(n.getId()==natureItemLocalNews.getId()){
                            exist=true;
                        }
                    }
                    if(!exist) {
                        temp.add(natureItemLocalNews);
                    }



                    for (NatureItemLocalNews n : MainActivity.ListForLocalNews) {
                        temp.add(n);
                    }
                    MainActivity.ListForLocalNews = new ArrayList<>(temp);
                    MainActivity.LastIdLocalNews = natureItemLocalNews.getId();
                    Last_Id_Local=natureItemLocalNews.getId();


                    SharedPreferences prefs1 =getSharedPreferences("CommonPrefs", MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs1.edit();
                    editor.putString("last_id_local_news", natureItemLocalNews.getId()+"");
                    editor.commit();


                    if(!exist) {
                        String ns = Context.NOTIFICATION_SERVICE;
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
                        int icon = R.mipmap.ic_lunch;
                        CharSequence tickerText = natureItemLocalNews.getSubject();
                        long when = System.currentTimeMillis();

                        int requestID = (int) System.currentTimeMillis();
                        Notification notification = new Notification(icon, tickerText, when);
                        Context context = getApplicationContext();
                        Intent notificationIntent = new Intent(MyAlarmService.this, PageOfNew2.class);
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        notificationIntent.putExtra("news_id", natureItemLocalNews.getId() + "");
                        notificationIntent.putExtra("news_title", natureItemLocalNews.getTitle());

                        notificationIntent.putExtra("news_updated_at", natureItemLocalNews.getDate());
                        notificationIntent.putExtra("news_attachment", natureItemLocalNews.getImgUrl());
                        notificationIntent.putExtra("news_text", natureItemLocalNews.getSubject());
                        notificationIntent.setAction("myString" + requestID);
                        PendingIntent contentIntent = PendingIntent.getActivity(MyAlarmService.this, requestID, notificationIntent, 0);
                        notificationIntent.setData((Uri.parse("mystring" + requestID)));
                        notification.setLatestEventInfo(context, natureItemLocalNews.getTitle(), "", contentIntent);
                        notification.flags += Notification.FLAG_ONGOING_EVENT;
                        notification.flags += Notification.FLAG_AUTO_CANCEL;
                        Uri notification1 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification1);

                        r.play();
                        mNotificationManager.notify(NOT_ID_2, notification);
                    }

                } else if (newsObj.getString("news_category_id").equals("3")) {
                    NatureItemEvents natureItemEvents = new NatureItemEvents();
                    natureItemEvents.setId(Integer.valueOf(newsObj.getString("news_id")));
                    natureItemEvents.setTitle(newsObj.getString("news_title"));
                    natureItemEvents.setDate(newsObj.getString("news_updated_at"));
                    natureItemEvents.setImgUrl(newsObj.getString("news_attachment"));
                    natureItemEvents.setSubject(newsObj.getString("news_text"));
                    natureItemEvents.setCityName(Temp.getCityName(Integer.valueOf(newsObj.getString("news_city_id"))));


                    List<NatureItemEvents> temp = new ArrayList<NatureItemEvents>();
                    boolean exist=false;
                    for (NatureItemEvents n : MainActivity.ListForEvents) {
                        if(n.getId()==natureItemEvents.getId()){
                            exist=true;
                        }
                    }
                    if(!exist) {
                        temp.add(natureItemEvents);
                    }

                    for (NatureItemEvents n : MainActivity.ListForEvents) {
                        temp.add(n);
                    }
                    MainActivity.ListForEvents = new ArrayList<>(temp);
                    MainActivity.LastIdEvents = natureItemEvents.getId();
                    Last_Id_Event=natureItemEvents.getId();

                    SharedPreferences prefs1 = getSharedPreferences("CommonPrefs", MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs1.edit();
                    editor.putString("last_id_events", natureItemEvents.getId()+"");
                    editor.commit();


                    if(!exist) {
                        String ns = Context.NOTIFICATION_SERVICE;
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
                        int icon = R.mipmap.ic_lunch;
                        CharSequence tickerText = natureItemEvents.getSubject();
                        long when = System.currentTimeMillis();

                        int requestID = (int) System.currentTimeMillis();
                        Notification notification = new Notification(icon, tickerText, when);
                        Context context = getApplicationContext();
                        Intent notificationIntent = new Intent(MyAlarmService.this, PageOfNew2.class);
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        notificationIntent.putExtra("news_id", natureItemEvents.getId() + "");
                        notificationIntent.putExtra("news_title", natureItemEvents.getTitle());

                        notificationIntent.putExtra("news_updated_at", natureItemEvents.getDate());
                        notificationIntent.putExtra("news_attachment", natureItemEvents.getImgUrl());
                        notificationIntent.putExtra("news_text", natureItemEvents.getSubject());
                        notificationIntent.setAction("myString" + requestID);
                        PendingIntent contentIntent = PendingIntent.getActivity(MyAlarmService.this, requestID, notificationIntent, 0);
                        notificationIntent.setData((Uri.parse("mystring" + requestID)));
                        notification.setLatestEventInfo(context, natureItemEvents.getTitle(), "", contentIntent);
                        notification.flags += Notification.FLAG_ONGOING_EVENT;
                        notification.flags += Notification.FLAG_AUTO_CANCEL;
                        Uri notification1 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification1);

                        r.play();
                        mNotificationManager.notify(NOT_ID_3, notification);
                    }

                } else if (newsObj.getString("news_category_id").equals("4")) {
                    NatureItemGasSatation natureItemGasSatation = new NatureItemGasSatation();
                    natureItemGasSatation.setNameGasStation(newsObj.getString("gas_station_name"));
                    natureItemGasSatation.setAddress(newsObj.getString("gas_station_address"));
                    String date = newsObj.getString("gas_station_date");
                    String date1 = date.substring(5);
                            natureItemGasSatation.setDate(newsObj.getString("gas_station_date"));
                    natureItemGasSatation.setDate(date1);
                    natureItemGasSatation.setId(Integer.valueOf(newsObj.getString("gas_station_id")));

                    List<NatureItemGasSatation> temp = new ArrayList<NatureItemGasSatation>();
                    boolean exist=false;
                    for (NatureItemGasSatation n : MainActivity.ListForGasStation) {
                        if(n.getId()==natureItemGasSatation.getId()){
                            exist=true;
                        }
                    }
                    if(!exist) {
                        temp.add(natureItemGasSatation);
                    }

                    for (NatureItemGasSatation n : MainActivity.ListForGasStation) {
                        temp.add(n);
                    }
                    MainActivity.ListForGasStation = new ArrayList<>(temp);
                    MainActivity.LastIdGasStation = natureItemGasSatation.getId();
                    Last_Id_Gas=natureItemGasSatation.getId();

                    SharedPreferences prefs1 = getSharedPreferences("CommonPrefs", MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs1.edit();
                    editor.putString("last_id_gas", natureItemGasSatation.getId()+"");
                    editor.commit();


                    if(!exist) {
                        String ns = Context.NOTIFICATION_SERVICE;
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
                        int icon = R.mipmap.ic_lunch;

                        CharSequence tickerText = "new notification";
                        long when = System.currentTimeMillis();

                        int requestID = (int) System.currentTimeMillis();
                        Notification notification = new Notification(icon, tickerText, when);
                        Context context = getApplicationContext();
                        Intent notificationIntent = new Intent(MyAlarmService.this, MainTabActivity.class);
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        notificationIntent.setAction("myString" + requestID);
                        PendingIntent contentIntent = PendingIntent.getActivity(MyAlarmService.this, requestID, notificationIntent, 0);
                        notificationIntent.setData((Uri.parse("mystring" + requestID)));
                        notification.setLatestEventInfo(context, "كازيات", "", contentIntent);
                        notification.flags += Notification.FLAG_ONGOING_EVENT;
                        notification.flags += Notification.FLAG_AUTO_CANCEL;
                        Uri notification1 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification1);
                        r.play();
                        mNotificationManager.notify(NOT_ID_4, notification);
                    }
                }

                       }// if null
            }// for


        }

    } catch (JSONException e) {
        e.printStackTrace();

    }
}