我正在构建一个可以按时计算屏幕的应用程序。首先,我构建一个服务,将计时器值00:00发送到MainActivity
,这是我的服务实现
public class MyService extends Service {
String time;
Intent io;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
try{
PowerManager power=(PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn=power.isScreenOn();
while(isScreenOn){
try{
StopWatch count=new StopWatch();
long timer=count.getTime();
long seconds=timer/1000;
time = String.format("%02d:%02d", (seconds % 3600) / 60, (seconds % 60));//creating time
}catch(Exception e){
e.printStackTrace();
}
io=new Intent("COUNTDOWN_UPDATED");
io.putExtra("countdown",time);
sendBroadcast(io);// sending time value
}
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
此处来自org.apache.commons.lang.time.StopWatch
的StopWatch类可以将计时器从0开始计数。
这是我的MainActivity
实施
Intent service=new Intent(this,MyService.class);
startService(service);
registerReceiver(updateGUI,new IntentFilter("COUNTDOWN_UPDATED"));
private BroadcastReceiver updateGUI=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
TextView countdown= (TextView)findViewById(R.id.textView1);
countdown.setText(intent.getExtras().getString("countdown"));
}
};
当我运行我的应用程序时,计数器没有运行它停留在00:00
答案 0 :(得分:0)
你的onCreate仅用于初始化,使用
@Override
public int onStartCommand(Intent i, int flags , int startId){
来自文档:
每次客户端通过调用显式启动服务时由系统调用 android.content.Context.startService,提供它提供的参数和唯一的整数标记 代表开始请求。不要直接调用此方法。 为了向后兼容,默认实现调用onStart并返回START_STICKY 或START_STICKY_COMPATIBILITY。 如果您需要在API级别5之前的平台版本上运行应用程序,则可以使用以下内容 在这种情况下处理旧的onStart回调的模型。 handleCommand方法由您适当地实现
虽然:
首次创建服务时由系统调用。不要直接调用此方法。 覆盖:服务中的onCreate()
如果您想要的是在文本视图中随时间变化值,为什么不使用值动画? 示例:
ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, percentage);
animator.addUpdateListener(new AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
prog.setText("Profile Progress: "+String.valueOf(animation.getAnimatedValue())+"%");
}
});
animator.setEvaluator(new TypeEvaluator<Integer>() {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
return Math.round((endValue - startValue) * fraction);
}
});
animator.setDuration(1500);
animator.start();
答案 1 :(得分:0)
虽然不是很明显,但在Android上,默认情况下会在应用程序的UI线程上执行Service
。
为了卸载工作,工具箱中存在一个方便的类IntentService
,用于启动您想在后台执行的工作。
在您的课程延长IntentService
后,覆盖onHandleIntent(Intent intent)
方法并将广播生成代码放在那里而不是onCreate
。
这将释放您的UI线程以继续按预期运行。
(在你的循环中,你永远不会更新isScreenOn
的值,所以它将始终保持不变!)