gpt4 book ai didi

android - 为什么这个处理程序(可运行)在服务上启动时会减慢我的应用程序?

转载 作者:行者123 更新时间:2023-11-29 22:24:56 24 4
gpt4 key购买 nike

我正在使用后台服务,它正在检索数据并在远程服务器上插入数据。好的,我把它放在后台服务上,因为我想在不减慢我的应用程序速度的情况下在后台完成它,但它正在减慢我的应用程序!

正如您将在代码中看到的那样,它有 60 秒的休眠时间,我的应用程序每 60 秒卡住 2/3 秒,我确定是这段代码,但我不知道如何解决它

public class MyService extends Service implements Runnable{
boolean serviceStopped;
RemoteConnection con; //conexion remota
List <Position> positions;
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
private Handler mHandler;
private Runnable updateRunnable = new Runnable() {
@Override public void run() {
//contenido
if (serviceStopped==false)
{
positions=con.RetrievePositions(settings.getString("login","")); //traigo todas las posiciones
if (positions.size()>=10) //si hay 10 borro la mas vieja
con.deletePosition(positions.get(0).getIdposition());
if (settings.getString("mylatitude", null)!=null && settings.getString("mylongitude", null)!=null)
con.insertPosition(settings.getString("mylatitude", null),settings.getString("mylongitude", null), formatDate(new Date()), settings.getString("login",""));
}
queueRunnable();//duerme
}
};
private void queueRunnable() {
//mHandler.postDelayed(updateRunnable, 60000); //envia una posicion al servidor cada minuto (60.000 milisegundos es un minuto)
mHandler.postDelayed(updateRunnable, 60000);
}

public void onCreate() {
serviceStopped=false;
settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
configEditor = settings.edit();
positions=new ArrayList<Position>();
con = new RemoteConnection();
mHandler = new Handler();
queueRunnable();
}

最佳答案

即使您创建了一个服务,也不意味着它会在单独的线程上运行。看看http://developer.android.com/reference/android/app/Service.html

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

请花一些时间阅读服务在 Android 中的实际工作方式 http://developer.android.com/guide/topics/fundamentals/services.html

因此,IntentService 和定时提醒可以作为解决方案。

关于android - 为什么这个处理程序(可运行)在服务上启动时会减慢我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6212459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com