教程Android的服务?教程、Android

2023-09-07 16:33:46 作者:ゞ高姿态旳浅唱

我做得很少有Android开发人员,我想知道是否有人在关于服务一个很好的教程。 我期待,使一个应用程序,启动,甚至在背景中继续循环下去。

I've done very little with android dev and I was wondering if anyone has a good tutorial in regards to Services. I'm looking to make an app that starts and continues to loop forever even in the background.

推荐答案

有上服务了丰富的资源,如果你做一个简单的谷歌搜索,所以我不打算解释服务是如何工作的。下面的code段使用未绑定到活动的服务。

There is a wealth of resources on Services if you do a simple google search so I'm not going to explain how services work. The code snippet below uses a service that isn't bound to the Activity.

我的方法使用一个定时器和一个任务,请注意我用的是重复,但是这是没有必要的任务。还有,你可以处理这个其他的方式。

My approach uses a Timer and a Task, note I use a task that repeats but this is not necessary. There are other ways you can approach this.

public class MyService extends Service {

    private Task retryTask;
    Timer myTimer;

    private boolean timerRunning = false;

    private long RETRY_TIME = 200000;
    private long START_TIME = 5000;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        myTimer = new Timer();
        myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
        timerRunning = true;

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!timerRunning) {
            myTimer = new Timer();
            myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
            timerRunning = true;
        }

        return super.onStartCommand(intent, flags, startId);

    }

    public class Task extends TimerTask {

        @Override
        public void run() {

            // DO WHAT YOU NEED TO DO HERE
        }

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        if (myTimer != null) {
            myTimer.cancel();

        }

        timerRunning = false;
    }
}

使用一个Intent然后您将开始从活动服务

You would then start the service from an Activity using an Intent

Intent intent = new Intent(WorkSelectionActivity.this,MyService.class);
        startService(intent);

希望这有助于

Hope this helps