Android启动服务多次

时间:2016-02-20 07:22:49

标签: android service

我正在制作送餐应用程序。在此,每当用户下订单时,向用户显示粘性通知并带有消息。该消息包含食物交付时间。所以我必须每10秒更新一次通知。 为此,我在用户下订单时创建了一个服务。通过orderId,我向API发送请求并获取数据并更新通知。我发送orderId与putExtra服务。每当我关闭应用程序时,服务都无法获得orderId,应用程序也会崩溃。

在下面的代码中,在onStartCommand中我使用了START_REDELIVER_INTENT。每当我关闭应用程序时,服务都没有运行,当我重新打开应用程序时,服务就开始了。但在我的情况下,服务也应该在用户关闭应用程序时运行。

我是新手使用android中的服务,我知道有些东西丢失了。请帮我。非常感谢。

public class NotificationService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used
    int notifyID = 1;
    String order_id  = "-1";


    @Override
    public void onCreate() {
        // The service is being created
        PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
        wakeLock.acquire();


        int delay = 3000;
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                if(!order_id.equals("-1"))
                    checkNotification(order_id);
            }
        }, 0, delay);


    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to startService()
        order_id = intent.getExtras().getString("order_id");

        return START_REDELIVER_INTENT;
    }
    @Override
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }
    @Override
    public void onRebind(Intent intent) {
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }
    @Override
    public void onDestroy() {
        // The service is no longer used and is being destroyed
    }

   private void checkNotification( String  order_id){
       String url = AppConfig.NOTIFICATION+"?order_id="+ order_id;
       Log.d("notification",url);
       JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url , new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {

               try {
                   Log.d("notification",response.toString());
                   if(response.getBoolean("status")){
                       JSONObject data = response.getJSONObject("data");

                       if(data.getString("order_status").equals("delivered")) {
                          next();
                       }else
                           showNotification(data.getString("order_status"),data.getString("message"),
                                   data.getString("ordered_time"),
                                   data.getString("distance"),data.getString("text_shown"));
                   }
               } catch (JSONException e) {
                   e.printStackTrace();
               }

           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {

           }
       });
       AppController.getInstance().addToRequestQueue(req);
   }

    private void next() {
        order_id = "-1";
        stopSelf();
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .cancelAll();
    }

     private  void showNotification( String order_status, String message ,
                                     String ordered_time,String distance, String away){

         RemoteViews remoteViews  = new RemoteViews(getPackageName(),R.layout.customnotification);
         remoteViews.setTextViewText(R.id.message, message);
         remoteViews.setTextViewText(R.id.ordered_time,ordered_time);
         remoteViews.setTextViewText(R.id.notification_distance, distance);
         remoteViews.setTextViewText(R.id.away, away);

         if(order_status.equals("reached")){
             remoteViews.setViewVisibility(R.id.separator_layout,View.GONE);
             remoteViews.setViewVisibility(R.id.notification_distance, View.GONE);
             remoteViews.setViewVisibility(R.id.away,View.GONE);
         }

        Intent intent = new Intent(this,OrderTrackAct.class);
        intent.putExtra("order_id",order_id);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_favicon)
                .setContentIntent(pIntent)
                .setContent(remoteViews);

        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification n;

        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            n = builder.build();
        } else {
            n = builder.getNotification();
        }

        n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        notificationmanager.notify(Integer.parseInt(order_id), n);
    }
}

0 个答案:

没有答案