簡體   English   中英

Android:在后台(服務)實現同步服務(通過http發布)的最佳方法是什么

[英]Android: What is the best way to implement a synchronization service (via http post) in background (service)

這是我在網絡服務(帶有一些HTTP POST請求)之間同步數據的基本服務的最新實現。

基本上,在應用程序執行期間,我想繼續將帖子(每1分鍾)發送到我的Web服務。

package com.example.testservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class HelloService extends Service {
    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;

    // Handler that receives messages from the thread
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            // empty
        }
    }

    @Override
    public void onCreate() {
        // Start up the thread running the service. Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block. We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                android.os.Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        // Get the HandlerThread's Looper and use it for our Handler
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);

        Log.d("SERVICE TEST onCreate", "Service created first time");
        Toast.makeText(this, "service created", Toast.LENGTH_SHORT).show();
        final long oneMinuteMs = 60 * 1000;
        Runnable eachMinute = new Runnable() {
            @Override
            public void run() {
                Log.d("SERVICE TEST run", "Each minute task executing");
                mServiceHandler.postDelayed(this, oneMinuteMs);
            }
        };

        mServiceHandler.postDelayed(eachMinute, oneMinuteMs);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // empty
        // If we get killed, after returning from here, restart
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // We don't provide binding, so return null
        return null;
    }

    @Override
    public void onDestroy() {
        Log.d("SERVICE TEST onDestroy", "Service destroyed");
    }
}
  • 這是Android中更好的方法嗎?
  • 使用onCreate方法來確保在應用程序生命周期內啟動一個同步任務是否正確?
  • 從我的第一個活動(MainActivity)啟動服務是否正確?

編碼:

package com.ncfsistemi.testservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, HelloService.class);
        startService(intent);       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

注意:我也嘗試過

TimerTask syncTask = new TimerTask()

但我有一些奇怪的行為(任務多次生成且時間控制錯誤)。 Android創建者不鼓勵TimerTask ...對嗎?

如果要根據某些時間表定期同步數據,最好的方法是使用SyncAdapter 看一下文檔,有很好的示例如何使用它。

如果要按需同步數據(例如,按活動的onResume方法),則可以使用IntentService

無論您做什么,都不要運行TimerTask 正如您自己發現的那樣,可能會發生意外的行為。 您可以在此處閱讀有關在Android OS下如何管理進程和線程的信息,並發現TimerTask很可能被殺死。 對於http操作,您必須使用Service因為它們具有較高的優先級。

暫無
暫無

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

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