Android - 定期背景服务

时间:2017-08-09 12:31:50

标签: java android

我想用2分钟创建一个周期性背景服务。当我批准登录我的应用程序并在我退出或杀死我的应用程序时终止服务时,我想启动服务

我试过这个,但它不起作用:

public class BackgroundService extends Service {

    public Context context = this;
    public Handler handler = null;
    public static Runnable runnable = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();

        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
                handler.postDelayed(runnable, 10000);
            }
        };

        handler.postDelayed(runnable, 15000);
    }

    @Override
    public void onDestroy() {
        /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
        //handler.removeCallbacks(runnable);
        Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:0)

int timerCount = 1;
private long period=120;

for (; timerCount <= period; timerCount++) {
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }

      if (timerCount == period) {
           stopSelf();
      }
}

使用此代码作为代码的计时器。

@Toorop是对的。尝试打印日志而不是Toast。

答案 1 :(得分:0)

只需在您的服务中添加以下功能,然后将Scheduletask()放入您的服务onCreate()方法

private final static int INTERVAL = 1000 * 60 * 2;
    private void Scheduletask()
    {
        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.d("Scheduletask","Running .................");
                new RetrieveDataTask().execute();
                handler.postDelayed(this, INTERVAL);
            }
        });
    }

    private class RetrieveDataTask extends AsyncTask<InputStream, Void, String> {

        protected String doInBackground(InputStream... urls) {
            return "Task Executed";
        }

        protected void onPostExecute(String result) {
            Log.d("Scheduletask",result);
        }
    }