如何使用共享pref静音媒体

时间:2018-01-18 12:44:40

标签: java android sharedpreferences

大家好,在我的应用程序中,有一个声音在应用程序启动时播放。我想让人们可以选择从主要活动设置屏幕中静音。

******使用给出的答案编辑****** 所以我在我的主要活动中创建了一个设置方法,现在启动一个名为Main2Activity的新活动,一旦我使其正常工作,这将成为我的设置活动。

@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);
}

接下来我有我的媒体播放器类

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();
}

正如答案所示,我现在疯了,所以可以使用名为App_Objects的约束类来访问媒体播放器。

    public class App_Objects {

//This is where i store my media player

public static MediaPlayer mp = new MediaPlayer();
}

接下来是我的新SettingsActivity取代了我的inflate视图

 @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");
            }
        }
    });
}

最后是我的启动活动,其中启动声音通过firebase网址播放,我再次添加了下面给出的答案。包括静音的方法

 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
    }
}
}

但现在声音接缝要静音了。从一开始,如果我转到我的设置活动并单击静音启动复选框,然后重新启动应用程序。该应用程序崩溃了,在我的控制台中给我致命

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)

1 个答案:

答案 0 :(得分:3)

我知道你想做什么。你可以通过使用声明媒体播放器静态来实现这一点。下面是您可以实现此目的的方法之一,您可以很好地构建此代码。我没有详细编写代码。

创建AppConstants课程并定义MediaPlayer staticaly。

public class AppConstants{

    public static MediaPlayer mp = new MediaPlayer();

}

创建SettingActivity活动类,您可以在其中为soundMute选项设置共享偏好值true / false。

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();

        }
    });

}

创建SplashActivity活动类,您可以在其中读取共享偏好以静音媒体播放器。

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();

}