您好我想在后台每秒运行一个函数。 因此,点击应用程序中的一个按钮后,计数器就会消失,每秒钟它会得+ 1,如果我切换到另一个应用程序并返回它应该仍然在后台计数。
我该怎么做
Alarmmanager? 处理程序?
最好的方法是什么。
答案 0 :(得分:0)
-Alarm Manager比使用handler + wakelock节省更多电量。但这是时间段的问题 ..
<强>实施强>
UpdateCountInSecond.java
public class UpdateCountInSecond extends Service {
int count=0
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//your work
count++;
return super.onStartCommand(intent, flags, startId);
}
}
创建一个方法名称: startServiceAlaramManager()并从您的主要活动或可能是您的启动画面调用它
public void startServiceAlaramManager(){
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, UpdateCountInSecond .class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//1 sec =1000 miliseconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
1000, pintent);
Toast.makeText(MainActivity.this, "alaram manager set", Toast.LENGTH_SHORT).show();
startService(new Intent(this, UpdateCountInSecond .class));
}
答案 1 :(得分:0)
您可以将TimerTask与服务一起使用。 请参阅this
这里是使用scheduleAtFixedAtFixedRate(...)函数的一个例子:
int counter=0;
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
counter++;
//Your code here
},
1000, //delay from start in milli seconds
1000 //update interval in milli seconds
);
答案 2 :(得分:0)
要在混音中添加其他选项,请尝试ScheduledExecutorService。创建一个runnable并使用scheduleAtFixedRate()
。我在圣诞节期间远离我的开发计算机,因此在应用程序背景化时,无法检查这是否仍然有效。上面的链接中有一个代码示例。