如何把Android activity变成service,具体举一个例子
时间: 2023-07-16 15:15:45 浏览: 59
将Android activity转换为service,需要将activity中的UI逻辑移动到service中,并且需要在service中创建一个独立的线程来处理逻辑。下面是一个简单的示例:
1. 创建一个新的service类,并继承Service类。
```java
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 在此处添加逻辑代码
return super.onStartCommand(intent, flags, startId);
}
}
```
2. 在MyService类中添加需要运行的逻辑代码,例如在后台播放音乐。
```java
public class MyService extends Service {
private MediaPlayer mMediaPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mMediaPlayer = MediaPlayer.create(this, R.raw.music);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
}
}
```
3. 在AndroidManifest.xml文件中声明服务。
```xml
<service
android:name=".MyService"
android:enabled="true"
android:exported="false" />
```
4. 在Activity中启动服务。
```java
Intent intent = new Intent(this, MyService.class);
startService(intent);
```
这样,当Activity启动时,服务就会在后台运行,播放音乐。如果Activity被销毁,服务仍将在后台运行,直到被停止或销毁。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)