Android之调用service的方法

发布时间 2023-04-20 13:35:31作者: laremehpe

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();
                //caller.customMet();//调用自定义方法
            }
            @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>