正如标题所说,在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();
}
}
}显然,我希望不断地监控这一点。使用带有TimerTask的Timer是否是持续监控这种情况的“最佳”、业界首选的方式?
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
getData();
}
}, 100);或者,有没有其他更好的方法来做到这一点,比如在安卓服务中使用while(true)循环?
谢谢!
发布于 2017-03-15 05:08:38
这有点取决于您对数据的计划用途。
如果您的数据的主要用例(如果不是唯一的)是更新您的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);
}
}在这里,我只是每5秒显示一次Toast,但是您可以在Runnable中更新周期和工作来执行所需的操作。
使用postDelayed()可以避免创建任何后台线程,并且不必处理返回到主应用程序线程的线程间通信来更新UI。
如果您的工作成本更高(例如,磁盘I/O、网络I/O),您可以使用TimerTask,尽管我更喜欢ScheduledExecutorService (在Java1.4版本中添加,更灵活)。
但是,如果您只需要在活动处于前台时进行此处理,则不需要Android服务。当你有需要完成的工作时,即使用户离开了你的用户界面,转而使用其他应用程序,服务也是适用的。
https://stackoverflow.com/questions/42795154
复制相似问题