简体   繁体   中英

How to mute media using shared pref

Hi guys in my app there is a sound that plays when the app starts up. i want give people the option to mute this from the main activity settings screen.

******Edit using answer given****** So i created a settings method in my main activity which now starts a new activity called Main2Activity this will be my settings activity once i get it working correctly.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.menuitem, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.Settings:

///No longer inflates settings xml.. Starts new settings activity instead
           startactivity(new Intent(MainActivity.this,Main2Activity.class))
            break;
    }
    return super.onOptionsItemSelected(item);
}

then next i have my media player class

public class harropMediaplayer {
MediaPlayer mp;
String media;
public harropMediaplayer(String media){
   this.media = media;
}
public void plysound() {

///My media player is now stored globally as suggested 
    mp = App_Objects.mp;
    String j =
            media.toString();
    Log.i("Url", j);
    try {
        mp.setDataSource(j);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

        Log.i("Sound playing", "Ok");

        mp.start();
    }

public void stopplying(){

    mp.stop();
    mp.release();
}

As suggested in the answer given ive now mad its so the media player can be accessed using a constraints class ive called App_Objects.

    public class App_Objects {

//This is where i store my media player

public static MediaPlayer mp = new MediaPlayer();
}

Next is my new SettingsActivity replacing my inflate view

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    final CheckBox btnradio = findViewById(R.id.btnmute);

    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedpreferences.edit();
    btnradio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (btnradio.isChecked()){

                editor.putBoolean("soundMute", b);
                editor.apply();
                Log.i( "onCheckedChanged: ","Activated");

            }
            else {

                editor.clear();
                editor.apply();

                Log.i("onCheckChanged: ","Deactivated");
            }
        }
    });
}

and finally my splash activity where the start up sound plays via a firebase url which again ive added the answer given below. including a method to mute the sound

 setContentView(R.layout.activity_splash__screen);

    database = FirebaseDatabase.getInstance();
    reference = database.getReference().child("tvthemetunes");

    getthemetune();

}



public void getthemetune() {

    Log.i ("Url Grab ", "Started");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i("Url Grab", "Searching database");
            long childrenCount = dataSnapshot.getChildrenCount();
            int count = (int) childrenCount;
            int randomNumber = new Random().nextInt(count);
            //Your random themeTune will be stored here
            for(DataSnapshot snap : dataSnapshot.getChildren())
            {
                int i =  0;

                    if(i == randomNumber)
                {
                    Themetune = snap.getValue(String.class);
                    try {

                        mp = new harropMediaplayer(Themetune);
                        ((TextView) findViewById(R.id.version)).setText("" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
                        ImageView view = findViewById(R.id.splash);
                        ImageView view1 = findViewById(R.id.rain);
                        Animation animFadeIn = AnimationUtils.loadAnimation(Splash_Screen.this, R.anim.fadein);
                        animFadeIn.reset();
                        mp.plysound();
 ///HERE IS WHERE I CALL MY NEW METHOD
                         volumeSetting();

                        view1.clearAnimation();
                        view1.startAnimation(animFadeIn);
                        RotateAnimation anim = new RotateAnimation(0.0f, 
360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

//Setup anim with desired properties
                        anim.setInterpolator(new LinearInterpolator());
                        anim.setRepeatCount(Animation.RELATIVE_TO_SELF); 
//Repeat animation indefinitely
                        anim.setDuration(1200); //Put desired duration per anim cycle here, in milliseconds

//Start animation
                        view.startAnimation(anim);

                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    int secondsDelayed = 2;
                    new Handler().postDelayed(new Runnable() {
                        public void run() {


                            startActivity(new Intent(Splash_Screen.this, 
 MainActivity.class));
                            finish();
                            mp.stopplying();

                        }
                    }, secondsDelayed * 2000);



                    break;
                }

            }

            }





        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

 private void volumeSetting(){

////MY NEW VOLUME MUTE METHOD INCLUDING THE FETCH SHARED PREF
    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);

    boolean bnSoundMute = sharedpreferences.getBoolean("soundMute",true);

    if(bnSoundMute){
        App_Objects.mp.setVolume(0,0); // for Mute
    }else{
        App_Objects.mp.setVolume(1,1);// for Unmute or full volume
    }
}
}

But now the sound seams to be muted. from the start and if i go to to my settings activity and click the mute startup check box then restart the app. The app crashes out giving my a fatal in my console

AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: h20music.p9p.harrop99.H20DroidApp_Amazon, PID: 2549
                                                                                    java.lang.IllegalStateException
                                                                                        at android.media.MediaPlayer.nativeSetDataSource(Native Method)
                                                                                        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1078)
                                                                                        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1039)
                                                                                        at h20music.p9p.harrop99.H20DroidApp_Amazon.harropMediaplayer.plysound(harropMediaplayer.java:29)
                                                                                        at h20music.p9p.harrop99.H20DroidApp_Amazon.Splash_Screen$1.onDataChange(Splash_Screen.java:84)
                                                                                        at com.google.android.gms.internal.zzeeq.zza(Unknown Source)
                                                                                        at com.google.android.gms.internal.zzegl.zzbwe(Unknown Source)
                                                                                        at com.google.android.gms.internal.zzegr.run(Unknown Source)
                                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

I got it what you want to do. you can achieve that by using declaring media player static. Below is the one of the way you can achieve this and you can well structure this code. I did't write code in details.

Create AppConstants class and define MediaPlayer staticaly.

public class AppConstants{

    public static MediaPlayer mp = new MediaPlayer();

}

Create SettingActivity Activity class where you can set sharedpreference value true/false for soundMute option.

public class SettingActivity{

    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();


    btnradio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            editor.putBoolean("soundMute", b);
            editor.apply();

        }
    });

}

Create SplashActivity Activity class where you can read sharedpreference to mute media player or not.

public class SplashActivity{

    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);

    boolean bnSoundMute = sharedpreferences.getBoolean("soundMute",true);

    if(bnSoundMute){
        AppConstants.mp.setVolume(0,0); // for Mute
    }else{
        AppConstants.mp.setVolume(1,1); // for Unmute or full volume
    }

    try {
        AppConstants.mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    AppConstants.mp.start();

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM