Android启动服务多次

Android启动服务多次,android,service,Android,Service,我正在制作一个食品配送应用程序。在这种情况下,每当用户下订单时,都会向用户显示一条带有消息的粘性通知。这条信息包含了食物配送时间。所以我必须每10秒更新一次通知。 为此,每当用户下订单时,我都创建了一个服务。通过orderId,我向API发送请求,获取数据并更新通知。我正在将orderId发送到putExtra服务。每当我关闭应用程序时,服务无法获取orderId,应用程序就会崩溃 在下面的代码中,我在onStartCommand中使用了START\u REDELIVER\u INTENT。这样

我正在制作一个食品配送应用程序。在这种情况下,每当用户下订单时,都会向用户显示一条带有消息的粘性通知。这条信息包含了食物配送时间。所以我必须每10秒更新一次通知。 为此,每当用户下订单时,我都创建了一个服务。通过orderId,我向API发送请求,获取数据并更新通知。我正在将orderId发送到putExtra服务。每当我关闭应用程序时,服务无法获取orderId,应用程序就会崩溃

在下面的代码中,我在onStartCommand中使用了START\u REDELIVER\u INTENT。这样,每当我关闭应用程序时,服务就不会运行,而当我重新打开应用程序时,服务就开始了。但在我的例子中,服务也应该在用户关闭应用程序时运行

我对安卓系统的服务还不熟悉,我知道它缺少了一些东西。请帮帮我。多谢

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);
    }
}
公共类NotificationService扩展服务{
int mStartMode;//指示在终止服务时的行为方式
IBinder mBinder;//用于绑定
布尔mAllowRebind;//指示是否应使用onRebind
int notifyID=1;
字符串顺序_id=“-1”;
@凌驾
public void onCreate(){
//正在创建服务
PowerManager-mgr=(PowerManager)getSystemService(Context.POWER\u服务);
PowerManager.WakeLock WakeLock=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,“MyWakeLock”);
wakeLock.acquire();
整数延迟=3000;
定时器=新定时器();
timer.scheduleAtFixedRate(新TimerTask(){
公开募捐{
如果(!order_id.等于(“-1”))
检查通知(订单号);
}
},0,延迟);
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
//由于调用startService()服务,服务正在启动
order_id=intent.getExtras().getString(“order_id”);
返回启动\u重新交付\u意图;
}
@凌驾
公共IBinder onBind(意向){
//客户端正在使用bindService()绑定到服务
返回mBinder;
}
@凌驾
公共布尔onUnbind(意图){
//所有客户端都已解除与unbindService()的绑定
返回mAllowRebind;
}
@凌驾
重新绑定时的公共无效(意图){
//客户端正在使用bindService()绑定到服务,
//已调用onUnbind()之后
}
@凌驾
公共空间{
//该服务已不再使用,正在被销毁
}
私有无效检查通知(字符串顺序\u id){
字符串url=AppConfig.NOTIFICATION+“?order\u id=“+order\u id;
Log.d(“通知”,url);
JsonObjectRequest req=newJSONObjectRequest(Request.Method.GET,url,new Response.Listener()){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
Log.d(“通知”,response.toString());
if(response.getBoolean(“status”)){
JSONObject data=response.getJSONObject(“数据”);
if(data.getString(“订单状态”)等于(“已交付”){
next();
}否则
showNotification(data.getString(“订单状态”)、data.getString(“消息”),
data.getString(“有序时间”),
data.getString(“距离”)、data.getString(“显示文本”);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
}
});
AppController.getInstance().addToRequestQueue(req);
}
二等兵{
订单id=“-1”;
stopSelf();
((NotificationManager)getSystemService(通知服务))
.cancelAll();
}
私有无效显示通知(字符串顺序状态、字符串消息、,
按顺序排列的字符串(时间、字符串距离、字符串距离){
RemoteViews RemoteViews=新的RemoteViews(getPackageName(),R.layout.customnotification);
setTextViewText(R.id.message,message);
setTextViewText(R.id.ordered\u time,ordered\u time);
remoteViews.setTextViewText(R.id.notification\u距离,距离);
setExtViewText(R.id.away,away);
if(订单状态等于(“达到”)){
remoteViews.setViewVisibility(R.id.separator\u布局,View.GONE);
remoteViews.setViewVisibility(R.id.notification\u距离,View.GONE);
remoteViews.setViewVisibility(R.id.away,View.GONE);
}
Intent Intent=新的Intent(这个,OrderTrackAct.class);
意向。额外(“订单id”,订单id);
intent.addFlags(intent.FLAG_ACTIVITY_SINGLE_TOP | intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingEvent pIntent=PendingEvent.getActivity(this,0,intent,PendingEvent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder=新建NotificationCompat.Builder(此)
.setSmallIcon(R.drawable.app_favicon)
.setContentIntent(pIntent)
.setContent(远程视图);
NotificationManager NotificationManager=(NotificationManager)getSystemService(通知服务);
通知n;
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.JELLY\u BEAN){
n=builder.build();
}否则{
n=builder.getNotification();
}
n、 flags |=Notification.FLAG_NO_CLEAR | Notification.FLAG_consuming_事件;
notificationmanager.notify(Integer.parseInt(order\u id),n);
}
}
t在哪里