首页 > 解决方案 > 在 android 应用程序中创建全时运行的后台服务的问题

问题描述

我正在创建一个 android 应用程序,该应用程序需要一个后台服务,该服务每 20 秒获取一次位置并将数据发送到 firebase。该服务必须在按钮单击时启动并连续运行,即使屏幕关闭并且应该在按钮单击时再次停止。起初,我尝试使用警报管理器,但它没有定期执行任务。接下来,我厌倦了使用异步任务,它正在调用一项服务,该服务正在执行将数据发送到 firebase 的任务。但是这种方法不适用于android 8+版本。然后后来我使用了类似的方法,但使用 JobIntent 服务,这种方法在 android 7(appo) 甚至在 android 8(lava) 中运行良好,但在 8+ 版本(appo reno 和 mi) 中可能是由于自定义操作系统,服务如果屏幕关闭,则不起作用。

我创建了一个名为打孔活动的活动,它有两个按钮,代码如下 -

  1. 此按钮使用每 20 秒调用一次服务的异步活动。
              @Override
              public void onClick(View v) {
                  if (punchedIn){
                      Toast.makeText(PunchActivity.this, "Already PunchedIn",
                              Toast.LENGTH_LONG).show();
                  }
                  else {
                                          timertask = new TimerTask() {
                                              @Override
                                              public void run() {
                                                  handler.post(new Runnable() {
                                                      public void run() {
                                                          Intent intent = new Intent(PunchActivity.this, BackgroundService.class);
                                                          //sendBroadcast(intent);
                                                          BackgroundService.enqueueWork(PunchActivity.this, intent);
  
                                                      }
                                                  });
                                              }
                                          };
                                          timer = new Timer();
                                          timer.schedule(timertask, 0, 20000);
                                      }
                                  }
  
                              }};
  1. 此按钮停止服务

        @Override
        public void onClick(View v) {
            punchedIn = false;
            Toast.makeText(getApplicationContext(),"PUNCHED OUT",Toast.LENGTH_SHORT).show();
            Log.d("Message","Process "+timer.toString());
            if (timer != null) {
                Log.d("Message","Process is killed");
                timer.cancel();
                timer = null;
                wakeLock.release();
            }
        }
    });```
    
    

JobIntentService 的代码如下

public class BackgroundService extends JobIntentService implements com.google.android.gms.location.LocationListener {

    private static Context mContext;
    private FusedLocationProviderClient fusedLocationProviderClient;
    public static String latitude = "", longitude = "";
    public static void enqueueWork(Context context, Intent work) {
        mContext = context;
        enqueueWork(context, BackgroundService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        //This task does the task of fetching location and sending data to firebase
        YourTask();
    }

}```

I have made use of power manager in punch activity but it did not work fine. So please give some suggestions or even rectify my approach if you find any issue, based on my use case . Any small clue could be helpful.


Thanks,

Vrashab

标签: android

解决方案


只需在如下循环中创建一个子线程并请求位置:

private HandlerThread thread = new HandlerThread("location_thread");
private Handler locationHandler = new Handler(thread.getLoop())
private boolean sholdStop = false
private Runnable locationRunnable = new Runnable() {
        while(!sholdStop) {
            // location logic
            ...
            Thread.sleep(20000);
        }
    });
// start to location per 20 seconds
public void startLocation() {
    locationHandler.removeCallbacks(locationRunnable);
    sholdStop = false;
    locationHandler.post(locationRunnable);
}

public void stopLocation() {
    sholdStop = true;
    locationHandler.removeCallbacks(locationRunnable);
}

但是如果你的应用被安卓系统杀掉了,这段代码就失效了。为了解决这个问题,你可能需要一些方法来让你的应用程序在后台运行时尽可能长的寿命。


推荐阅读