在 Android 中实现长时间运行、持续监控任务的行业首选方法是什么?



就像标题所说,在Android中实现长时间运行,持续监控任务的行业首选方法是什么?

例如,有一种方法可以获得小区信号强度:

public void getData(){
int cellSignalStrength = 0;
TelephonyManager telephonyManager = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
List<CellInfo> cellInfos = telephonyManager.getAllCellInfo();
for(CellInfo info : cellInfos){
if(info instanceof CellInfoCdma){
cellSignalStrength = ((CellInfoCdma) info).getCellSignalStrength().getLevel();
} else if(info instanceof CellInfoGsm){
cellSignalStrength = ((CellInfoGsm) info).getCellSignalStrength().getLevel();
} else if(info instanceof CellInfoLte){
cellSignalStrength = ((CellInfoLte) info).getCellSignalStrength().getLevel();
} else if(info instanceof CellInfoWcdma){
cellSignalStrength = ((CellInfoWcdma) info).getCellSignalStrength().getLevel();
}
}
}

显然,我想不断监控这一点。使用具有TimerTaskTimer是否是持续监控这一点的"最佳"、行业首选方式?

Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
getData();
}
}, 100);

或者,是否有其他更好的方法来做到这一点,比如Android服务中的while(true)循环?

谢谢!

这有点取决于您计划的数据用途。

如果你的主要(如果不是唯一的)数据用例是更新你的UI,并且工作本身很便宜(处理<1ms),那么最便宜的使用方法是postDelayed()

/***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.post;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class PostDelayedDemo extends Activity implements Runnable {
private static final int PERIOD=5000;
private View root=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
root=findViewById(android.R.id.content);
}
@Override
public void onStart() {
super.onStart();
run();
}
@Override
public void onStop() {
root.removeCallbacks(this);
super.onStop();
}
@Override
public void run() {
Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
.show();
root.postDelayed(this, PERIOD);
}
}

在这里,我只是每五秒显示一次Toast,但您可以更新Runnable中的周期和工作以执行所需的操作。

使用postDelayed()可以避免创建任何后台线程,并且必须处理返回到主应用程序线程的线程间通信以更新 UI。

如果你的工作会更昂贵(例如,磁盘I/O,网络I/O),你可以使用TimerTask,尽管我更喜欢ScheduledExecutorService(在1.4左右添加到Java中,更灵活)。

但是,如果您只需要在活动处于前台时进行此处理,则您不需要Android服务。服务适用于需要完成的工作,即使用户离开你的 UI 并前往其他应用也是如此。

最新更新