Android - 计时器内部服务

时间:2014-01-30 12:44:40

标签: android

我在Android服务中有计时器我需要启动一次此计时器,并且我有多次调用此服务。每次我调用startService()时,服务都会启动新的计时器(计时器执行其工作的次数与调用startService()一样多。)

这是代码

    private TimerTask notificationTask = new TimerTask() {
    @Override
    public void run() {
        posNotification();
    }
};

    @Override 
public void onCreate() {
    super.onCreate();
    notificationTimer.schedule(notificationTask, 1000L, 10 * 1000L);
}

1 个答案:

答案 0 :(得分:1)

您可以将值保留在共享首选项或采用全局变量。最初将其设置为0。调用服务时,请检查该值。如果为0则启动计时器并将全局值设置为1.因此,下次不会启动计时器。这对你有意义吗?请查看我准备的示例代码,如果它能解决您的问题,请告诉我:

package com.example.timerinservice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    Button btnStartService;
    Context context;
    int service_count = 0;

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

        context = MainActivity.this;
        btnStartService = (Button) findViewById(R.id.buttonStartService);

        btnStartService.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, TimerService.class);
                intent.putExtra("servicecount", service_count);
                context.startService(intent);
                service_count++;
            }
        });
    }

}

-----------------
package com.example.timerinservice;

public class GlobalVariable {
    public static boolean TIMER_STYARTED = false;
}
-----------------
package com.example.timerinservice;

import java.util.Timer;
import java.util.TimerTask;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class TimerService extends IntentService {

    Timer notificationTimer;
    int get_service_count = 0;

    public TimerService() {
        super("timerservice");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        get_service_count = intent.getExtras().getInt("servicecount");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if(!GlobalVariable.TIMER_STYARTED){
            notificationTimer = new Timer();
            notificationTimer.schedule(notificationTask, 1000L, 10 * 1000L);

            GlobalVariable.TIMER_STYARTED = true;
        }

    }

    private TimerTask notificationTask = new TimerTask() {
        @Override
        public void run() {
           //posNotification(); 
            Log.d("INSIDE","run() of TimerTask for: "+get_service_count);
        }
    };
}