Android:在后台(服务)实现同步服务(通过http post)的最佳方式是什么

时间:2014-10-01 07:08:07

标签: android android-service

这是我用于在Web服务之间同步数据的基本服务的最后一个实现(带有一些HTTP POST请求)。

基本上,在应用程序执行期间,我想继续将帖子(每1分钟)发送到我的网络服务。

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 ......对吗?

1 个答案:

答案 0 :(得分:1)

如果您想根据某些计划定期同步数据,最好的方法是使用SyncAdapter。看看文档,有很好的例子如何使用它。

如果要按需同步数据(例如,在activity的onResume方法上),则可以使用IntentService

无论你做什么,都不要运行TimerTask。正如您自己发现的那样,可能会发生意外行为。您可以阅读here,了解如何在Android操作系统下管理进程和线程,并查看可能会导致TimerTask被杀死。对于http操作,您必须使用Service,因为它们具有高优先级。