android上的后台进程计时器

VTR*_*015 3 service android timer

我正在尝试运行一个进程计时器并让它在android的后台运行(单击按钮开始).

计时器必须在30秒内,甚至应该在后台继续增加应用程序(主页按钮和电源/屏幕关闭).

我怎样才能做到这一点?我试过服务和处理程序,但没有工作......

编辑

我的服务跟踪(30秒处理)

public class TrackingService extends IntentService {

    private Handler mHandler;
    private Runnable mRunnable;

    public TrackingService() {

        super("TrackingService");

    }

    public TrackingService(String name) {

        super(name);

    }

    @Override
    protected void onHandleIntent(Intent intent) {

        long timer = 30000;

        mHandler = new Handler();
        mRunnable = new Runnable() {

            @Override
            public void run() {

                    //TODO - process with update timer for new 30 sec

                    mHandler.postDelayed(this, timer);

            }
        };

        mHandler.postDelayed(mRunnable, timer);

    }

}
Run Code Online (Sandbox Code Playgroud)

我的点击按钮:

mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        //TODO - start first time and it continued every 30 seconds and continue in the background
        startService(Intent intent = new Intent(this, TrackingService.class));

    }
});
Run Code Online (Sandbox Code Playgroud)

Str*_*der 9

好的,首先,我真的不知道我的问题是否正确.但我想你想要一个每30秒执行一次的计时器,如果我没有弄错的话.如果是,请执行以下操作:

AlarmManager

注意:此类提供对系统警报服务的访问.这些允许您安排应用程序在将来的某个时间运行.当警报响起时,已被注册为它的目的是通过系统广播,自动启动目标程序,如果它已经运行.设备处于休眠状态时会保留已注册的警报(如果设备在此期间关闭,则可以选择将设备唤醒),但如果设备关闭并重新启动,则会清除设备.

例:

在你的onClick()注册你的计时器:

int repeatTime = 30;  //Repeat alarm time in seconds
AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, processTimerReceiver.class);   
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Repeat alarm every second
processTimer.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),repeatTime*1000, pendingIntent); 
Run Code Online (Sandbox Code Playgroud)

和你的processTimerReceiver类:

//This is called every second (depends on repeatTime)
public class processTimerReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        //Do something every 30 seconds
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记在Manifest.XML中注册接收器

<receiver android:name="processTimer" >
   <intent-filter>
       <action android:name="processTimerReceiver" >
       </action>
   </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

如果您想要取消闹钟:使用它来执行此操作:

//Cancel the alarm
Intent intent = new Intent(this, processTimerReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助你.

PS:如果这不是您想要的,请将其留在评论中,或者如果有人想要编辑,请执行此操作.