Почему мой сервис выполняется один раз, а затем не работает даже в фоновом режиме? - PullRequest
0 голосов
/ 17 декабря 2018

Вот мой код класса MapService. Есть ли какое-нибудь решение для моей проблемы?

public class MapService extends Service
    {
        GPSTracker gpsTracker;
        double lat,lon;
        SharedPreferences sharedPreferences;
        String phone,mrequestBody,url="";
        @Override
        public void onCreate() {//onCreate Method ,initializing .
            // TODO Auto-generated method stub
            super.onCreate();
            gpsTracker = new GPSTracker(MapService.this);
            sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            Notification notification = new Notification();
            startForeground(1, notification);
        } 

// в этой функции переопределения я написал свой код для размещения сообщения, но он выполняется только один раз, когда я предполагаюпроблема где-то здесь, пожалуйста, дайте ваши ценные предложения.

@Override
public int onStartCommand(Intent intent, int flags, int startId)
        {
//acquiring latitude and longitude
          lat=  gpsTracker.getLongitude();
           lon= gpsTracker.getLatitude();

           phone= sharedPreferences.getString("phone_number","");
            Toast.makeText(MapService.this, lat + " latitude ," + lon + " longitude ," + phone + " phone ", Toast.LENGTH_LONG).show();
    //        RequestQueue queue = Volley.newRequestQueue(this);
            final JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("latitude", lat);
                jsonObject.put("longitude", lon);
                jsonObject.put("phone",phone);;
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
    //parsing json Onject to string 
            mrequestBody = jsonObject.toString();
     Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
                final JsonObjectRequest jsonObjReq = new JsonObjectRequest(
                        Request.Method.POST, url, null,
                        new Response.Listener<JSONObject>()
                        {
                            @Override
                            public void onResponse(JSONObject response)
                            {
                                Log.i("location", response.toString());
                                //pDialog.dismiss();
                                Toast.makeText(MapService.this, (String) String.valueOf(response), Toast.LENGTH_SHORT).show();
                            }
                        }, new Response.ErrorListener()
                {

    //Volley error response
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Error: " + error.getMessage()
                        );
                      //  pDialog.dismiss();
                       Toast.makeText(MapService.this,"ServiceMap :"+error.getMessage(),Toast.LENGTH_LONG).show();
                    }
                })
                {
                    /**
                     * Passing some request headers
                     * */
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("content-type", "application/json");
                        return headers;
                    }
    //getbody function of volley POST request
                    @Override
                    public byte[] getBody() {
                        try {
                            return mrequestBody == null ? null : mrequestBody.getBytes("utf-8");
                        } catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                                    mrequestBody, "utf-8");
                            return null;

                        }
                    }
                };
    // Adding request to request queue
                Volley.newRequestQueue(this).add(jsonObjReq);
                return Service.START_NOT_STICKY;
        }

Здесь, в приведенном ниже упражнении, я призываю мой сервис создать экземпляр

Intent serviceIntent = new Intent(Service_Men_LoginActivity.this,MapService.class);
                              //serviceIntent.setAction("com.example.lenovo.khadam.MapService");

Единственная проблема заключается в том, что он выполняется один раз всеtoast в MapService показывается только один раз, но я хочу, чтобы эта служба выполнялась, пока я не вызову его stopService Method. И я не хочу, чтобы эта служба была службой переднего плана, потому что пользователю не должно отображаться уведомление.

...