1.创建一个简单的MyService继承Service
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 处理Service的逻辑
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
// 如果Service需要被绑定,则返回一个IBinder实例
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
2.在MyService的onCreate方法中创建通知
String CHANNEL_ID = "channel_id_wifi";
String CHANNEL_NAME = "channel_name_wifi";
int NOTIFICATION_ID = 110;
NotificationChannel notificationChannel;
Notification notification;
@Override
public void onCreate() {
// 创建通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.build();
} else {
notification = new NotificationCompat.Builder(this, "my_service_channel")
.setContentTitle("前台服务")
.setContentText("服务正在运行")
.setSmallIcon(R.drawable.ic_launcher_background) // 替换为您的通知图标资源ID
.build();
}
startForeground(NOTIFICATION_ID, notification);
super.onCreate();
}
在onCreate中创建通知的优势是无论该服务是通过startService还是bindService启动的该服务,都会调用onCreate方法,所以通知都可以正常创建,除此之外,onCreate方法仅会调用一次,可以有效避免重复创建。当然,针对定制化的通知,也可根据需求在onStartCommand和onBind中进行创建。
3.在onDestroy中停止前台服务
public void onDestroy() {
stopForeground(true);
super.onDestroy();
}
4.在AndroidManifest.xml注册文件中,添加通知权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
5.如果当前版本是Android10的话,Android应用程序获得读写存储卡权限的情况下,需要在AndroidManifest.xml的application标签下声明
android:requestLegacyExternalStorage="true"
6.在MainActivity中启动服务
① startService:
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
② bindService:
Intent serviceIntent = new Intent(this, MyService.class);
connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 当Service连接成功时调用
}
@Override
public void onServiceDisconnected(ComponentName name) {
// 当Service连接断开时调用
}
};
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
值得注意的是,如果采用的是bindService的方法,一定记得在MainActivity的onDestroy方法中及时解绑,避免内存泄漏。
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}