1

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

正如您将在代码中看到的那样,它的睡眠时间为 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();
        }
4

1 回答 1

2

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

请注意,服务与其他应用程序对象一样,在其托管进程的主线程中运行。这意味着,如果您的服务要执行任何 CPU 密集型(例如 MP3 播放)或阻塞(例如网络)操作,它应该生成自己的线程来完成这项工作。更多信息可以在进程和线程中找到。IntentService 类可作为 Service 的标准实现使用,它有自己的线程来安排要完成的工作。

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

因此,IntentService预定警报可以成为这里的解决方案。

于 2011-06-02T09:12:43.060 回答