MainActivity.java :
private BackgroundMusicService caller;
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent svc = new Intent(getApplicationContext(), BackgroundMusicService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
startService(svc);
bindService(svc, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
BackgroundMusicService.BackgroundMusicServiceBinder binder = (BackgroundMusicService.BackgroundMusicServiceBinder) service;
caller = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("onServiceDisconnected");
}
}, Context.BIND_AUTO_CREATE);
}
}
BackgroundMusicService.java :
public class BackgroundMusicService extends Service {
private static final String CHANNEL_ID = "channelID";
Notification customNotification;
private final IBinder binder = new BackgroundMusicServiceBinder();
public class BackgroundMusicServiceBinder extends Binder {
public BackgroundMusicService getService() {
return BackgroundMusicService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("bind");
return binder;
}
@Override
public void onCreate() {
super.onCreate();
setNotification();
startForeground(200, customNotification);
}
private void setNotification() {
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.custom_notification);
customNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.more)
.setCustomContentView(rv)
.build();
NotificationChannel channel = null;
NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
}
public void customMet(){
System.out.println("test");
}
}
AndroidManifest.xml
<Application>
<service
android:name=".service.BackgroundMusicService"
android:exported="true"
android:enabled="true"
/>
</Application>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!