如何销毁/杀死服务?

时间:2019-03-30 17:46:24

标签: java android android-service

我让我的应用程序运行用于抖动检测的服务,但是在MainActivity中,我有一个用于注销用户的按钮,在该按钮中,我必须注销并终止检测抖动事件的服务。

我在MainActivity中注销的方法是:

checkboxes

但是,如果我在注销后摇动设备,该服务将识别出摇动,就好像它不会立即杀死它:

list_of_names <- tibble("Name" = c("Name1", "Name2", "Name3"), 
                        "0 pt" = c("Criteria 0 name1", "Criteria 0 name2", "Criteria 0 name3"), 
                        "1 pt" = c("Criteria 1 name1", "Criteria 1 name2", "Criteria 1 name3"), 
                        "2 pt" = c("Criteria 2 name1", "Criteria 2 name2", "Criteria 2 name3"))

vectorx <- c('input$Name1_id', 'input$Name2_id', 'input$Name3_id')

listx <- sapply(sapply(1:3, function(i) { paste0("input$Name", i, "_id")}),function(x) NULL)

mycollapse <- lapply(1:nrow(list_of_names), function(i) {
  bsCollapsePanel(paste0(list_of_names$Name[i]),
                  awesomeCheckboxGroup(inputId = paste0(list_of_names$Name[i], "_id"),label = NULL,
                                       choices = as.character(list_of_names[i,2:4]),
                                       status = "success", width = "75%"))
})
mycollapse[["id"]] <- "collapseID"
mycollapse[["multiple"]] <- FALSE
mycollapse[["open"]] <- "Name1"

#### UI ----------

ui <- dashboardPage(
  dashboardHeader(title = "Minimal Example"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard", tabName = "Dashboard", icon = icon("dashboard"), 
               selected = TRUE))),   
  dashboardBody(
    fluidPage(
      column(6, shinyjs::useShinyjs(), withSpinner(uiOutput("Data"))))))

server <- function(input, output, session) {

  #approach 1 make a reactive list to store the inputs
  values <- reactiveValues(mylist = list())
  output$Data <- renderUI({
    tagList(
      do.call(bsCollapse, args = mycollapse) %>% return(),
      actionButton("Save", "Save"))
  })

  #approach 1 observe changes in the inputs (including deselect of all, which would not work if you use observeEvent as it does not fire if all boxes are FALSE)
 observe({ lapply(1:3, function(i) {
    values$mylist[[paste0('Name', i, '_id', sep = '')]] <- input[[paste0('Name', i, '_id', sep = '')]]
})
  })
   ####################



  observeEvent(input$Save, {
    confirmSweetAlert(session, inputId = "Save_SWAL", title = 
                        "Save?", text = "Are you sure?",
                      type = "warning", danger_mode = TRUE, btn_labels = c("Cancel", "Yes, save please"))
  })


  observeEvent(input$Save_SWAL, {
    if (isTRUE(input$Save_SWAL)) {


      #approach 1 simply print the minimums in the reactive list
      print("#approach 1")
      print(sapply(values$mylist, min) )

      ##### I tried for over 1.5 hour, but I could not get an sapply block working on strings called "input$Name1_id" etc 
      ## normally I would use eval(parse(text = 'input$Name1_id')) to read what the input is, but for some reason it will not work with a list of names
      ## This makes a named yet empty list for instance:  
      ## listx <- sapply(sapply(1:3, function(i) { paste0("input$Name", i, "_id")}),function(x) NULL)
      ## with the idea that I could then try to sapply over the names with eval(parse()) construct, but it doesn't return the minimums

      # keeps printing empty 'list()'
      # print(sapply(eval(parse(text = names(listx))), min))


      ##this keeps printing the names of vectorx
      # print(sapply(vectorx, min))


      #approach 2 run an lapply over all the inputs without the need to store them
      print("#approach 2")
      lapply(1:3, function(i) {
        if(!!length(input[[paste0('Name', i, '_id', sep = '')]])) {  ## !!length means it is NOT an empty list, so then we want the min
          min(input[[paste0('Name', i, '_id', sep = '')]]) %>% print()
        }
      })

    }
  })
}

shinyApp(ui, server)

onDestroy方法中的代码是:

public void signOutAndFinish(){
    //Stop Shakeservice
    Intent intent = new Intent(this, ShakeService.class);
    stopService(intent);
    //Go to login activity
    Intent iLoginView = new Intent(this, LoginActivity.class);
    startActivity(iLoginView);
}

如何终止服务,以便注销服务时退出服务?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以通过服务的onDestroy()方法向您的活动发送回广播,然后注销。

以下是上述想法的一些示例代码:

为您服务:

@Override
public void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent();
    intent.setAction("com.example.broadcast.MY_NOTIFICATION");
    intent.putExtra("data","Notice for logout!");
    sendBroadcast(intent);
}

这是为了您的活动

private BroadcastReceiver br = new MyBroadcastReceiver();

@Override
public void onCreate() {
  IntentFilter filter = new IntentFilter("com.example.broadcast.MY_NOTIFICATION");
  registerReceiver(br, filter);
}

@Override
public void onDestroy() {
  unregisterReceiver(br);
}

// An inner class at your activity
public class MyBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "MyBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        YourActivity.this.finish();
        // or do anything you require to finish the logout...
    }
}

答案 1 :(得分:0)

  

但是,如果我在注销后摇晃设备,则服务会识别出摇晃

然后大概您没有清理服务的Sensor方法中的onDestroy()东西。

  

如何终止服务,以便注销服务时死亡?

您正在这样做。但是,如果您在服务中进行了某些设置,例如侦听SensorManager中的事件,则通常需要在服务的onDestroy()中对其进行清理。