您好,我想每秒在后台运行一个函数。
因此,在应用程序中单击一个按钮后,计数器将消失,每秒将变为+ 1,如果我切换到另一个应用程序并取回它,它应该仍在后台计数。
我该怎么做呢
报警经理?
处理程序?
做这个的最好方式是什么。
最佳答案
几个月前..
我对此进行了研究,发现了这一点
-与使用处理程序+唤醒锁相比,警报管理器节省更多电量。但这是时间问题。
实现方式:
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));
}