gpt4 book ai didi

java - Activity 关闭时服务重新启动

转载 作者:行者123 更新时间:2023-12-02 02:46:42 25 4
gpt4 key购买 nike

此服务会使设备在 10 秒后振动,但当 Activity 关闭或从最近的应用程序中删除应用程序时,该服务将重新启动。

public class Vibrar extends Service {

@Override
public IBinder onBind(Intent p1) {
// TODO: Implement this method
return null;
}

int delay = 10000; //milliseconds

@Override
public void onCreate() {
// TODO: Implement this method
Toast.makeText(getApplicationContext(),"created",Toast.LENGTH_SHORT).show();
super.onCreate();
Vibrar();
}

public void Vibrar() {
new Handler().postDelayed(new Runnable() {
public void run() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
}
}, delay);
}
}

我已尝试使用值为return START_STICKSTART_NOT_STICKonStartComand 方法,但它不断重新启动或立即终止。

即使该应用程序已从最近的应用程序中删除,我也希望它能从中断处继续。有什么办法可以做到这一点吗?

最佳答案

我见过许多程序员犯了使用匿名处理程序的错误。

使用这个:

    Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
if(System.currentMillis() - getLastVibrationTime() > delay){
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
saveVibrationTime();
}
}
};
handler.postDelayed(runnable,10000);

然后销毁:

handler.removeCallbacks(runnable);

这将确保当您退出应用程序或服务时,处理程序也被取消。

希望这有帮助。

关于java - Activity 关闭时服务重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com