Android - 简单的重复后台任务

时间:2015-10-05 19:39:15

标签: android repeat background-service

我正在尝试运行简单的后台服务,这将是每一段时间检查日期做我想要的,但我有创建的问题。我在谷歌叔叔的帮助下,但他不能帮助我。尽管AndroidManifest.xml行<service android:name=".HelloService" />public class HelloService extends Service { },我仍然没有任何代码。我怎么写呢?我不想使用警报。

1 个答案:

答案 0 :(得分:0)

您可以将Service设置为无限期运行,例如while循环。在该循环中,您可以使用类似Thread.sleep()的内容来制作Service方式一段时间。或者你也可以使用Handler,具体取决于你想要达到的目标。

Dunno为什么你不想使用闹钟,但这也应该可以胜任。

有关Handler here的更多信息。

编辑:使用Handler的示例代码:

public class MyActivity extends Activity { 

    private Handler handler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // The method you want to call every now and then.
            yourMethod();
            handler.postDelayed(this,2000); // 2000 = 2 seconds. This time is in millis.
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_slider);

        handler.postDelayed(runnable, 2000); // Call the handler for the first time.

    }

    private void yourMethod() { 
        // ... 
    } 
    // ...
}

P.S。:使用此解决方案,您的代码将在Activity被销毁后停止。