Androidstudio定一个服务每隔一秒加1
时间: 2024-05-15 22:13:41 浏览: 9
可以通过创建一个 Service,在其中使用 Handler 来实现每隔一秒加1的功能,具体代码如下:
```java
public class MyService extends Service {
private Handler handler = new Handler();
private int count = 0;
private Runnable runnable = new Runnable() {
@Override
public void run() {
count++;
Log.d("MyService", "count: " + count);
handler.postDelayed(this, 1000);
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.postDelayed(runnable, 1000);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
handler.removeCallbacks(runnable);
super.onDestroy();
}
}
```
在 Activity 中启动服务:
```java
startService(new Intent(this, MyService.class));
```
需要注意的是,使用完服务后记得要停止服务,否则会一直在后台运行:
```java
stopService(new Intent(this, MyService.class));
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)