我正在尝试在Android服务中实现Counter timer,但它没有启动。
服务等级
public class ServiceSample extends Service {
int timer = 0;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
new CountDownTimer(20000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer++;
Toast.makeText(ServiceSample.this, "" +timer, Toast.LENGTH_SHORT).show();
Log.d("count", "" + timer);
}
@Override
public void onFinish() {
}
}.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
}
主要活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(MainActivity.this,ServiceSample.class));
}
}
服务正在启动,因为它显示Toast,但未显示Timer,并且在Logcat中也未显示任何错误。 而且onDestroy都没有运行。
并且我已在清单文件中添加了服务条目