我有一个服务类型类,它在onCreate方法中启动一个timertask,我需要在用户按下按钮时从MainActivity中停止计时器。我知道我必须在我的服务中保留对计时器的引用,但我无法弄清楚如何做到这一点并需要一些帮助,拜托!
请看看我的代码
package com.example.timertest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
startService(new Intent(this, TimeService.class));
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.button){
// i need here to call mTimer.cancel() in TimeService.class
//
}
}
}
//这里是TimeService.java
package com.example.timertest;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimeService extends Service {
public Timer mTimer;
private Handler mHandler = new Handler();
long NOTIFY_INTERVAL = 60 * 1000 * 1; // 1 min
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
if (mTimer != null) {
mTimer.cancel();
} else {
mTimer = new Timer();
}
mTimer.scheduleAtFixedRate(new RefreshDataTimerTask(), 0, NOTIFY_INTERVAL);
}
class RefreshDataTimerTask extends TimerTask {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), getDateTime(), Toast.LENGTH_LONG).show();
}
});
}
private String getDateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
}
//和在manifest中注册的服务
<service android:name=".TimeService"/>
我试图调用mTimer.cancel(),但得到了一个空引用,因为我似乎已经创建了一个服务类的新实例。
这个例子显示了每分钟有一个日期和时间的Toast,我希望当例如15秒过去时我按下按钮,取消定时器并从头开始再次开始计数60秒。在这项服务中,我有许多其他的东西,如通知,频道,共享偏好等等,所以如果我只能使用计时器对象操作会很好。
看看这个API documentaion和this。在您可以直接访问服务方法之后,有一些如何将bind
服务到活动的示例。
成功绑定后,您可以在服务中添加方法来停止计时器:
public void stopMyTimer() {
mTimer.cancel();
}
并从Activity
调用此方法
这可能不是最佳做法,但您可以通过直接引用该类来访问公共值:
TimeService.mTimer.cancel()
哪个应该起作用,因为Services的功能类似于Singletons,因为每次调用startService都应该调用同一个实例。