当响应在线程中更改时如何停止服务?

我在服务内部的后台运行服务,正在使用API​​的改造响应。这是我的下面的代码。

public class BookingService extends Service {
BackgroundService service;
Intent responseComplete;
int bookingId, userId, driverId;
String serviceStatus= "";


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
        if (!service.isRunning()) {
        service.start();
        service.isRunning = true;
        bookingId = TruckApplication.ReadIntPreferences(SharedPrefData.PREF_BOOKING_ID);
        userId = Integer.parseInt(TruckApplication.ReadStringPreferences(SharedPrefData.PREF_UserId));
            driverId = TruckApplication.ReadIntPreferences(SharedPrefData.PREF_DRIVER_ID);
           service = new BackgroundService();
    }
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
    super.onCreate();
    service = new BackgroundService();
    Log.d("CREATED>>>>", "Created");
}

@Override
public void onDestroy() {
    super.onDestroy();

    try {
        if (service.isRunning) {
            service.interrupt();
            service.isRunning = false;
            service = null;
        }
        else {

        }
    } catch (Exception e){
        Log.d("@@Exc", e.getMessage());
    }
}

class BackgroundService extends Thread {
    public boolean isRunning = false;
    public long milliSecs = 3000;
    Runnable runTask = new Runnable() {
        @Override
        public void run() {
            isRunning = true;
            while (isRunning) {
                try {
                    Log.d("HANDLER_RUNNABLE>>>>", "HANDLER");
                    bookingConfirm();
                    Thread.sleep(milliSecs);


                } catch (InterruptedException e) {
                    e.printStackTrace();
                    isRunning = false;
                }
            }
        }
    };
    public boolean isRunning()

    {
        return isRunning;
    }

    @Override
    public void run() {
        super.run();
        runTask.run();
    }
    public void bookingConfirm(){

        ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
        Call<BookingStatus> call = apiInterface.bookingStatus(userId,bookingId );

        Log.d("@@userId", String.valueOf(userId));
        Log.d("@@bookingId", String.valueOf(bookingId));

        call.enqueue(new Callback<BookingStatus>() {
            @Override
            public void onResponse(Call<BookingStatus> call, Response<BookingStatus> response) {
                if (response.isSuccessful()){

                    BookingStatus bookingStatus  = response.body();
                    assert bookingStatus != null;
                    if (bookingStatus.getSuccess()) {

                        if (bookingStatus.getMessage().equals("Booking Approved")){
                            Toast.makeText(getApplicationContext(), bookingStatus.getMessage(), Toast.LENGTH_SHORT).show();
                            int userOTP = bookingStatus.getUserBookingStatus().getUserOTP();
                            onDestroy();

                            Intent intent = new Intent(BookingService.this, ShowDriverLocation.class);
                            intent.putExtra("bookingId", bookingId);
                            intent.putExtra("userOTP", userOTP);
                            intent.putExtra("TruckName", bookingStatus.getUserBookingStatus().getTruckName());
                            intent.putExtra("truckNo", bookingStatus.getUserBookingStatus().getTruckNumber());
                            intent.putExtra("driverNo", bookingStatus.getUserBookingStatus().getDriverNumber());
                            intent.putExtra("driverName", bookingStatus.getUserBookingStatus().getDriverName());
                            Log.d("@@userOTP", String.valueOf(userOTP));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }   if (bookingStatus.getMessage().equals("Booking Pending")){
                            StartForeground();

                        }    if (bookingStatus.getMessage().equals("Booking Rejected")){
                            onDestroy();

                        }
                        else {
                          Toast.makeText(getApplicationContext(), bookingStatus.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), bookingStatus.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
                else {
                   Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<BookingStatus> call, Throwable t) {
                Log.d("Error", "errorhere");
            }
        });
    }
}

private void StartForeground() {
    Intent intent = new Intent(this, TabbarActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

    String CHANNEL_ID = "channel_location";
    String CHANNEL_NAME = "channel_location";

    NotificationCompat.Builder builder = null;
    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        builder.setChannelId(CHANNEL_ID);
        builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
    } else {
        builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
    }

    builder.setContentTitle("Ride");
    builder.setContentText("Your Ride Request is Pending");
    Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
    builder.setSound(notificationSound);
    builder.setAutoCancel(true);
    builder.setSmallIcon(R.drawable.order_selector);
    builder.setContentIntent(pendingIntent);
    Notification notification = builder.build();
    startForeground(101, notification);
}
}

我想停止此服务并在状态为预订批准时启动新服务,但在应用程序中,一次又一次,该应用程序正在启动服务没有停止,请帮助我,我将感谢您的每一个答复,谢谢

评论
  • Mered
    Mered 回复

    You should call stopSelft instead of call onDestroy() try this code

    if (response.isSuccessful() && service != null){
    
                        BookingStatus bookingStatus  = response.body();
                        assert bookingStatus != null;
                        if (bookingStatus.getSuccess()) {
    
                            if (bookingStatus.getMessage().equals("Booking Approved")){
                                Toast.makeText(getApplicationContext(), bookingStatus.getMessage(), Toast.LENGTH_SHORT).show();
                                int userOTP = bookingStatus.getUserBookingStatus().getUserOTP();
                                onDestroy();
    
                                Intent intent = new Intent(BookingService.this, ShowDriverLocation.class);
                                intent.putExtra("bookingId", bookingId);
                                intent.putExtra("userOTP", userOTP);
                                intent.putExtra("TruckName", bookingStatus.getUserBookingStatus().getTruckName());
                                intent.putExtra("truckNo", bookingStatus.getUserBookingStatus().getTruckNumber());
                                intent.putExtra("driverNo", bookingStatus.getUserBookingStatus().getDriverNumber());
                                intent.putExtra("driverName", bookingStatus.getUserBookingStatus().getDriverName());
                                Log.d("@@userOTP", String.valueOf(userOTP));
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                stopForeground(true);
                                stopSelf();
                            }   if (bookingStatus.getMessage().equals("Booking Pending")){
                                StartForeground();
    
                            }    if (bookingStatus.getMessage().equals("Booking Rejected")){
                                onDestroy();
    
                            }
                            else {
                              Toast.makeText(getApplicationContext(), bookingStatus.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), bookingStatus.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }