我需要在2分钟后调用一个方法。我已经尝试过处理程序和计时器,但是当应用程序关闭时它不起作用。然后我有呼叫计时器在服务中,单击按钮即可启动服务,并在2分钟后停止服务。它可以工作,但问题是服务有时会自行调用。下面是我的代码。
MyService类别
public class MyService extends Service {
private static Retrofit retrofit = null;
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d("message", "start");
}
public void onFinish() {
Log.d("message", "finish");
callMyMethod();
stopService(new Intent(MyService.this, MainActivity.class));
}
}.start();
}
我从那里开始服务的MainActivity类。
stopService(new Intent(getContext(), MyService.class));
startService(new Intent(getContext(), MyService.class));
显现
<service android:name="MyService" android:enabled="true" android:exported="true"/>
注意:我只想按一下按钮即可致电服务,并在2分钟后停止服务。请寻求帮助以解决此问题,或者如果除服务之外还有其他好的解决方案。
catspeake
皈依舞
相关分类