Android每X秒运行一次服务线程

Android每X秒运行一次服务线程,android,multithreading,timer,Android,Multithreading,Timer,我想在Android服务中创建一个每X秒运行一次的线程 我目前正在使用postdelayed方法,但它似乎确实落后于我的应用程序 @Override public int onStartCommand(Intent intent, int flags, int startId){ super.onStartCommand(intent, flags, startId); startRepeatingTask(); return startId; } private

我想在Android服务中创建一个每X秒运行一次的线程

我目前正在使用postdelayed方法,但它似乎确实落后于我的应用程序

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    super.onStartCommand(intent, flags, startId);

    startRepeatingTask();

    return startId;
}

private final static int INTERVAL = 20000; //20 milliseconds
Handler m_handler = new Handler();

Runnable m_handlerTask = new Runnable()
{
     @Override 
     public void run() {
         // this is bad
          m_handler.postDelayed(m_handlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    m_handlerTask.run(); 
}

void stopRepeatingTask()
{
   m_handler.removeCallbacks(m_handlerTask);
   stopSelf();
}
我想做一个像这样的新线程:

public void threadRun()
{
    Thread triggerService = new Thread(new Runnable(){
        public void run(){
            Looper.prepare();
            try{
                    //do stuff here?

            }catch(Exception ex){
                    System.out.println("Exception in triggerService Thread -- "+ex);
            }//end catch


        }//end run
    }, "aThread");
    triggerService.start();      

    //perhaps do stuff here with a timer?
    timer1=new Timer();

    timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL);
}

我不确定以一定间隔运行后台线程的最佳方法,敬请谅解

每隔几秒钟启动一个
runnable
会有一些延迟,不管你用什么方式分割它,不是吗?我不明白为什么
处理程序
不能正常工作

但你可能会遇到一些麻烦,因为你

void startRepeatingTask()
{
    m_handlerTask.run(); 
}
相反,您应该使用处理程序并执行以下操作:

void startRepeatingTask()
{
    m_handler.post(m_handlerTask); 
}

(顺便说一句,Java中的约定是使用驼峰大小写,而不是蛇形大小写。因此,它应该是mHandler,而不是m_handler,等等。只是告诉你,因为它可能会让一些人更容易阅读代码。)

下面是我如何运行重复线程的,你会看到它每1秒循环一次。我认为这种方法没有滞后性

final Thread t = new Thread(new RepeatingThread());
t.start();
班级:

import android.os.Handler;

public class RepeatingThread implements Runnable {

    private final Handler mHandler = new Handler();

    public RepeatingThread() {

    }

    @Override
    public void run() { 
        mHandler.postDelayed(this, 1000);       
    }
}

有许多替代方法可以做到这一点。就个人而言,我更喜欢使用:


MyService.java

public class MyService extends Service {

    public static final int notify = 5000;  //interval between two services(Here Service run every 5 seconds)
    int count = 0;  //number of times service is display
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
                }
            });

        }

    }
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, MyService.class)); //start service which is MyService.java
    }
}
MainActivity.java

public class MyService extends Service {

    public static final int notify = 5000;  //interval between two services(Here Service run every 5 seconds)
    int count = 0;  //number of times service is display
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
                }
            });

        }

    }
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, MyService.class)); //start service which is MyService.java
    }
}
AndroidManifest.xml

AndroidManifest.xml

<service android:name=".MyService" android:enabled="true" android:exported="true"></service>


嘿,我基本上是这样做的,我用了一个TimerTask:)嗨,我用这个,它工作得很好,但我如何停止任务?@Kevin,使用它,即使在应用程序关闭时它也会运行吗?小心,我有一种只启动一次的方法,没有延迟这种方式你能提供一些解释这个代码吗?这里的提示是使用服务并实现一个计时器,在一段时间间隔内运行TimerTask。我这里的例子是我每5秒钟吃一次吐司和时间