【发布时间】:2021-08-27 22:36:41
【问题描述】:
我正在学习 Java 和 Android 开发。现在我正在制作一个一旦启动就会创建服务的应用程序。然后我希望服务根据我在应用程序中按下的按钮执行操作。
这是我的服务类。
public class ServiceClass extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
// Issue is here. I cannot use findViewById
Button start_stop_button = (Button) findViewById(R.id.button2);
start_stop_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
// stop the wifi manager
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
我的想法是我可以设置一个监听器,这样当我按下按钮时 onClick() 就会执行。但这行不通,因为该服务未附加到任何活动以知道 id "button1" 是什么。
然后我考虑保留一个类变量并更新它。这些看起来相当简单,但是我不确定如何让服务检查变量的状态以进行更改。我可以把它放在一个 for 循环中继续检查,但我觉得有更好的方法存在。
tldr;我有一个启动服务的应用程序。我希望我的应用程序能够关闭并且服务仍然运行。但我想在我的应用程序中有一个启动/停止按钮来触发服务。
【问题讨论】:
标签: java android android-studio