Android 如何每1分钟在后台运行一次服务

Android 如何每1分钟在后台运行一次服务,android,service,Android,Service,我需要每1分钟启动一次在后台运行的服务,即使我的应用程序没有运行 以下是代码的一部分: ` 我用定时器每1分钟处理一次电话 final Handler handler = new Handler(); Timer timer = new Timer(); TimerTask hourlyTask = new TimerTask() { @Override public void run() { handl

我需要每1分钟启动一次在后台运行的服务,即使我的应用程序没有运行

以下是代码的一部分: `

我用定时器每1分钟处理一次电话

    final Handler handler = new Handler();

    Timer timer = new Timer();
    TimerTask hourlyTask = new TimerTask() {

        @Override
        public void run() {
                handler.post(new Runnable() {
                @SuppressWarnings("unchecked")
                public void run() {
                    try {

                        Intent intent = new Intent(ServiceMain.this, LocationMonitoringService.class);
                        startService(intent);


                        //   Toast.makeText(testServiceMain.this, "test", Toast.LENGTH_SHORT).show();


                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });


        }
    };


    timer.schedule(hourlyTask, 3, 1000 * 10);


}
`
谢谢

您需要使用android的Alarm Manager,它将在您在Alarm Manager中设置的时间启动您的服务

看看这个开发者指南


您需要使用android的Alarm Manager,它将在您在Alarm Manager中设置的时间内启动您的服务

看看这个开发者指南


Android TimerTask示例
TimerTask表示任务将在指定的时间运行,并且只运行一次或重复执行。
创建新类new TimerTask
有两种方法的TimerTask

    -->
        1 .scheduledExecutionTime() // Repeat Task
        2 .schedule() //Only once
        Timer singleTask=new Timer();
        Timer repeatTask=new Timer();

        int singleTaskInterval=3000; // 3 sec
        int repeatInterval=10000; // 10 sec

        // this task for specified time only once it will run
        singleTask.schedule(new TimerTask(){
@Override
public void run(){
// Here do something
// This task will run 3 sec only once.
        }
        },1000);

        // this task for specified time it will run Repeat
        repeatTask.scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
// Here do something
// This task will run every 10 sec repeat
        }
        },0,repeatInterval);

        When your activity went to destroy or stop.you should cancel this task
        -->-->
@Override
protected void onDestroy(){
        super.onDestroy();
        if(singleTask!=null){
        singleTask.cancel();
        }
        if(repeatTask!=null){
        repeatTask.cancel();
        }
        }
        Activity Code

/**
 * @author vijayakumar
 */
public class AndroidMADQAActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    Timer singleTask = new Timer();
    Timer repeatTask = new Timer();
    int singleTaskInterval = 3000; // 3 sec
    int repeatInterval = 10000; // 10 sec

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        singleTask.schedule(new TimerTask() {
            @Override
            public void run() {
// Here do something
// This task will run 3 sec only once.
            }
        }, 1000);
        repeatTask.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
// Here do something
// This task will run every 10 sec repeat
            }
        }, 0, repeatInterval);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (singleTask != null) {
            singleTask.cancel();
        }
        if (repeatTask != null) {
            repeatTask.cancel();
        }
    }
}

Android TimerTask示例
TimerTask表示任务将在指定的时间运行,并且只运行一次或重复执行。
创建新类new TimerTask
有两种方法的TimerTask

    -->
        1 .scheduledExecutionTime() // Repeat Task
        2 .schedule() //Only once
        Timer singleTask=new Timer();
        Timer repeatTask=new Timer();

        int singleTaskInterval=3000; // 3 sec
        int repeatInterval=10000; // 10 sec

        // this task for specified time only once it will run
        singleTask.schedule(new TimerTask(){
@Override
public void run(){
// Here do something
// This task will run 3 sec only once.
        }
        },1000);

        // this task for specified time it will run Repeat
        repeatTask.scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
// Here do something
// This task will run every 10 sec repeat
        }
        },0,repeatInterval);

        When your activity went to destroy or stop.you should cancel this task
        -->-->
@Override
protected void onDestroy(){
        super.onDestroy();
        if(singleTask!=null){
        singleTask.cancel();
        }
        if(repeatTask!=null){
        repeatTask.cancel();
        }
        }
        Activity Code

/**
 * @author vijayakumar
 */
public class AndroidMADQAActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    Timer singleTask = new Timer();
    Timer repeatTask = new Timer();
    int singleTaskInterval = 3000; // 3 sec
    int repeatInterval = 10000; // 10 sec

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        singleTask.schedule(new TimerTask() {
            @Override
            public void run() {
// Here do something
// This task will run 3 sec only once.
            }
        }, 1000);
        repeatTask.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
// Here do something
// This task will run every 10 sec repeat
            }
        }, 0, repeatInterval);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (singleTask != null) {
            singleTask.cancel();
        }
        if (repeatTask != null) {
            repeatTask.cancel();
        }
    }
}
你为什么要这样做

Timer timer = new Timer() ;
MyTimer myTask = new MyTimer (timer) ;
int firstSart = 1000 ; // it means after 1 second.
int period = 1000*60 ; //after which the task will repeat;(After 60 seconds)
timer.schedule(myTask, firstSart, period) ;//the time specified in millisecond
为计时器创建单独的类,并将服务放在那个里,或者在通用代码的情况下,您可以通过构造函数-

import java.util.Timer;
import java.util.TimerTask;
/* This is scheduler class which have scheduleing operation logic*/
public class MyTimer extends TimerTask {

    Timer timer ;
    int count = 0 ;

    public MyTimer () {

    }

    public MyTimer ( Timer timer ) {
        this.timer = timer ;
    }

    public void toDo() {
        Intent intent = new Intent(ServiceMain.this, LocationMonitoringService.class);
        startService(intent);
    }

    @Override
    public void run () {
        toDo () ;

        if (count > 10) {
            // this is the condition when you want to stop the task here i have not incriges the value of count
            //so it will run in infinite loop.
            timer.cancel () ;
        }
    }

}
你为什么要这样做

Timer timer = new Timer() ;
MyTimer myTask = new MyTimer (timer) ;
int firstSart = 1000 ; // it means after 1 second.
int period = 1000*60 ; //after which the task will repeat;(After 60 seconds)
timer.schedule(myTask, firstSart, period) ;//the time specified in millisecond
为计时器创建单独的类,并将服务放在那个里,或者在通用代码的情况下,您可以通过构造函数-

import java.util.Timer;
import java.util.TimerTask;
/* This is scheduler class which have scheduleing operation logic*/
public class MyTimer extends TimerTask {

    Timer timer ;
    int count = 0 ;

    public MyTimer () {

    }

    public MyTimer ( Timer timer ) {
        this.timer = timer ;
    }

    public void toDo() {
        Intent intent = new Intent(ServiceMain.this, LocationMonitoringService.class);
        startService(intent);
    }

    @Override
    public void run () {
        toDo () ;

        if (count > 10) {
            // this is the condition when you want to stop the task here i have not incriges the value of count
            //so it will run in infinite loop.
            timer.cancel () ;
        }
    }

}
在代码中使用

    Timer timer ;
    int count = 0 ;

 if (count > 10) {
            // Enter your code 
            //It will run N number of time
            timer.cancel () ;
        } 
在代码中使用

    Timer timer ;
    int count = 0 ;

 if (count > 10) {
            // Enter your code 
            //It will run N number of time
            timer.cancel () ;
        } 

与其定期启动服务,不如让服务继续运行,并在服务内部运行计时器,以预定的时间间隔完成工作。与其定期启动服务,不如让服务继续运行,并在服务内部运行计时器,在预定的时间间隔内完成工作。