簡體   English   中英

在Android應用程序中進行服務器通信的具有后台服務的最佳方法

[英]best way to have a background service making server communication in android application

目前,我正在開發一個可監視某些用戶行為的android應用程序,這些行為是位置,加速度計,圖片,短信和彩信信息。

我面臨着一個艱巨的問題。 我正在使用具有警報管理器的服務從這些服務中讀取信息。

警報管理器如下:

@Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        Intent intent = new Intent(this, WorkingService.class);
        PendingIntent pintent = PendingIntent.getService(
                getApplicationContext(), 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        calendar.setTimeInMillis(System.currentTimeMillis());
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                15000, pintent);

    }

這將每15秒調用一次此類的onstart命令。

@SuppressWarnings("static-access")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);

在此服務的onStartCommand中,我從具有位置更新和其他信息的服務中讀取內容。

問題在於,這在功率方面非常昂貴。 有人告訴我,服務數量不會對電池產生重大影響,但可以通過警報管理器訪問這些服務。 我在這個問題上有什么選擇? 並且可以確認我的應用中消耗更多電量的東西實際上是警報管理器服務。

如果是這樣,那么定期讀取服務並將數據發送到我的Web服務中的更好方法是什么?

為什么不嘗試使用線程? 這樣的事情會起作用:

Thread t = new Thread()

{

    @Override

    public void run()

    {

        while (true)

            {

            try
                {
                Thread.sleep(100);

                } catch (InterruptedException ie)
                {
                    fThreadRunning = false;
                    ie.printStackTrace();
                }   
            }
        }
    };
t.start();

顯然,您越閱讀該位置,您的電池消耗就越多,我建議您研究一下Android DDMS ,看看哪些線程導致了應用程序中最大的電池消耗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM