我正在制作一个游戏应用程序,但是即使关闭游戏,音乐仍会继续播放。如何停止?以及如何在单击按钮后转到其他活动来更改背景音乐

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.rysk);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}


这是我的主要活动(PlayActivity.class)

Intent svc=new Intent(this, BackgroundSoundService.class);
        startService(svc);


我想在单击按钮并转到CatActivity时更改音乐

最佳答案

您应该使用registerReceiver,unregisterReceiver。

可能对您有帮助。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button btn_startservice;
    private Button btn_stopservice;
    private TextView tv_servicecounter;
    ServiceDemo myService;
    boolean isBound;

    BroadcastReceiver broadcastRec = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int datapassed = intent.getIntExtra("value", 0);
            tv_servicecounter.setText(String.valueOf(datapassed));

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_servicecounter = (TextView) findViewById(R.id.tv_activity_main_count);
        btn_startservice = (Button) findViewById(R.id.btn_activity_main_startservices);
        btn_stopservice = (Button) findViewById(R.id.btn_activity_main_stopservices);



        btn_startservice.setOnClickListener(
                new View.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                    @Override
                    public void onClick(View v) {

                        Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
                        if (!isBound) {
                            bindService(objIntent, myConnection, Context.BIND_AUTO_CREATE);
                            isBound = true;
                            startService(objIntent);
                        } else {
                            isBound = false;
                            unbindService(myConnection);
                        }
                    }
                }

        );

        btn_stopservice.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);

                        if (isBound) {
                            isBound = false;
                            unbindService(myConnection);
                            stopService(objIntent);

                        } else {
                            stopService(objIntent);
                        }



                    }
                }
        );
    }

    @Override
    protected void onResume() {
        registerReceiver(broadcastRec, new IntentFilter("USER_ACTION"));
        super.onResume();
    }

    @Override
    protected void onStop() {
        this.unregisterReceiver(broadcastRec);
        super.onStop();
    }

    private ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            myService = ((ServiceDemo.MyLocalBinder) service).getService();
            isBound = true;
        }

        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(myConnection);
            isBound = false;
        }
    }

}


还有ServiceDemo.java

public class ServiceDemo extends Service {
    int i;
    private MyThread mythread;
    public boolean isRunning = false;
    Notification notification;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mythread = new MyThread();

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();

        if (!isRunning) {
            mythread.start();
            isRunning = true;
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mythread.interrupt();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    }

    public void sendBrodcastMsg(int value) {
        Intent intent = new Intent();
        intent.setAction("USER_ACTION");
        intent.putExtra("value", value);
        sendBroadcast(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    class MyThread extends Thread {
        static final long DELAY = 100;

        @Override
        public void run() {
            while (isRunning) {
                try {
                    i++;
                    Thread.sleep(DELAY);
                    sendBrodcastMsg(i);
                    shownotification();
                } catch (InterruptedException e) {
                    isRunning = false;
                    e.printStackTrace();
                }
            }
            stopSelf();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void shownotification() {
        Intent in = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), in, 0);

        notification = new NotificationCompat.Builder(this)
                .setContentTitle(String.valueOf(i))
                .setContentText(String.valueOf(i))
                .setSmallIcon(R.drawable.musicplayer)
                .setContentIntent(pIntent)
                .setAutoCancel(true).build();
        ;

        startForeground(101, notification);

    }

    public class MyLocalBinder extends Binder {
        ServiceDemo getService() {
            return ServiceDemo.this;
        }
    }

    private final IBinder myBinder = new MyLocalBinder();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return myBinder;
    }
}


将这两行放在清单中。

<service android:name=".ServiceDemo"
            android:enabled="true"/>

10-07 12:54
查看更多