切换活动时如何中断播放声音?

时间:2020-10-23 16:33:07

标签: android android-studio

我有一个列表数组适配器。我为“ arraylist”的每个元素使用模板布局。我通过“ CustomArrayAdapter.java”类中的图像上定义的“ onclicklistener”播放声音。 顺便说一句,我在相关活动中将“ onStop()”定义为替代。 当我点击图片时,声音会播放,但是当我通过点击手机上的主屏幕按钮测试切换活动时, 声音继续播放。 我在Customarraylist.java中的代码的一部分:

ImageView playIconSecondLanguageImage =      (ImageView)list_layout.findViewById(R.id.playIconsecondLanguageImageviewId);  playIconSecondLanguageImage.setImageResource(customWord.getmPlayIconImageId();
playIconSecondLanguageImage.setOnClickListener(new View.OnClickListener() {
     @Override
    public void onClick(View v) {
 releaseMediaPlayer();// to stop another playing when another start instantly
     mMediaPlayer = 
    MediaPlayer.create(v.getContext(),customWord.getmSecondLanguageSoundId());
      mMediaPlayer.start();
      mOnCompletionListener();
            }
        });

以及我在NumberActivity.java中的部分代码:

  }//End of Oncreat

   public void releaseMediaPlayer(){
        if(mediaPlayer!=null)
        {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

   protected void onStop() {
        super.onStop();
        releaseMediaPlayer();
    }
}//End of  class NumbersActivity
问题是NumbersActivity.java中的mediaplayer与我在其中定义的mediaplayer不同 “ Customarraylist.java”播放声音。 我的CustomArrayAdapter.java是:

package com.example.customarrayadapter;

import android.app.Activity;
import android.app.Application;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;

public class CustomArrayAdapter extends ArrayAdapter<CustomWord> {
//    States
    private int mColorId;
    private MediaPlayer mMediaPlayer;
//  to avoid creat new object(here,new medaPlayer), this codes below take out from the Onclick listener
//    and define here******************
    private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            Toast.makeText(getContext(),"Play finished!",Toast.LENGTH_SHORT).show();
            //                        check is it need to mPlayer anymore or not,to free up memeory usage by the player
            releaseMediaPlayer();
        }
    };


    //****************************************
//    need Constructor
    public CustomArrayAdapter(Activity context, ArrayList<CustomWord>arrayList,int colorId){
        super(context,0,arrayList);
        this.mColorId = colorId;
    }

//    use getView override method to move elements of arraylist one by one by its position,to listview
//    getView method, steps:
//    a. get position of elements in "customWord"(get one from 2 elements in CustomWord" Type,and pass to
//    arraylist of type CustomWord,then 2 from 2 elemnts moves),by "position" by "getItem(position)"

//    b. prepare a view (convertview),to locate our "list_layout", in it
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//        a.
        final CustomWord customWord = getItem(position);
//        Define "list_layout"  view, to get  "convertView" layout in it
        View list_layout = convertView;
//        if list_layout is null,then put "customlist_layout" in it
        if(list_layout==null){
            list_layout = LayoutInflater.from(getContext()).inflate(R.layout.customlist_layout,parent,false);
        }
//        1 image (source image) + 2 words + 2 image(language flags) +  2 images(olay icon), in customlist_layout.xml so ,so need 2 textview + 1 imageview

        // Find the ImageView in the list_item.xml layout with the ID list_item_icon
//         ImageView 1 (SourceImage)
        ImageView ImageSourceiconView = (ImageView) list_layout.findViewById(R.id.ImageSourceViewId);
        // set the image to iconView
        ImageSourceiconView.setImageResource(customWord.getmDataResourceId());

        //        put elements(2 elements) in "CustomWord" one by one into (2 textviews),each textview (one textview to second textview)
//      textview 1
        TextView secondLanguage_tv = (TextView)list_layout.findViewById(R.id.SecondLanguageId_Textview_ListView);
        secondLanguage_tv.setText(customWord.getmSecondLanguageString());
//      textview 2
        TextView defualtLanguage_tv = (TextView)list_layout.findViewById(R.id.DefualtLanguageId_Textview_ListView);
        defualtLanguage_tv.setText(customWord.getmDefualtLanguageString());

//        Default Flag Language Image View
        //         ImageView 2 (Default Flag)
        ImageView defaultLanguageFlag = (ImageView) list_layout.findViewById(R.id.DefaultLanguageFlag);
        // set the image to iconView
        defaultLanguageFlag.setImageResource(customWord.getmDefaultLanguageFlag());

//        Second Flag Language ImageView
        //         ImageView 3 (Second Flag)
        ImageView secondLanguageFlag = (ImageView) list_layout.findViewById(R.id.SecondLanguageFlag);
        // set the image to iconView
        secondLanguageFlag.setImageResource(customWord.getmSecondLanguageFlag());

        // source playIcon imageview

        ImageView playIconDefualtLanguageImage = (ImageView)list_layout.findViewById(R.id.playIcondefaultLanguageImageViewId);
        playIconDefualtLanguageImage.setImageResource(customWord.getmPlayIconImageId());

        playIconDefualtLanguageImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                releaseMediaPlayer();// to stop another playing when another start instantly
                mMediaPlayer = MediaPlayer.create(v.getContext(),customWord.getmDefaultLanguageSoundId());
                mMediaPlayer.start();
                mOnCompletionListener();
            }
        });
        // 2nd play icon image set
        ImageView playIconSecondLanguageImage = (ImageView)list_layout.findViewById(R.id.playIconsecondLanguageImageviewId);
        playIconSecondLanguageImage.setImageResource(customWord.getmPlayIconImageId());

        playIconSecondLanguageImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                releaseMediaPlayer();// to stop another playing when another start instantly
                mMediaPlayer = MediaPlayer.create(v.getContext(),customWord.getmSecondLanguageSoundId());
                mMediaPlayer.start();
                mOnCompletionListener();
            }
        });


        //        Default Sound Language Image View
        //         ImageView 4 (Default Language sound)

//         set color of layout by mcolorId to sync with name of category in main layout.xml
        View textContainer  = list_layout.findViewById(R.id.CustomListId);
//        ContextCompat is for creat color from getColor
//        getColor get color of getContext Object and its color integer id
        int color = ContextCompat.getColor(getContext(),mColorId);
        textContainer.setBackgroundColor(color);


        return list_layout;
    }//End of getviw

    private void mOnCompletionListener() {
    }

    public void releaseMediaPlayer(){
        if(mMediaPlayer!=null)
        {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }


    public void setmMediaPlayer(MediaPlayer mMediaPlayer) {
        this.mMediaPlayer = mMediaPlayer;
    }
    public MediaPlayer getmMediaPlayer() {
        return mMediaPlayer;
    }

}

enter image description here

3 个答案:

答案 0 :(得分:0)

您必须控制活动生命周期,然后必须根据需要打开/关闭声音。

enter link description here

答案 1 :(得分:0)

您可以使用Interface来满足您的需求:

创建一个Interface并调用它(例如 PlayerCallBack ):

public interface PlayerCallBack {
    void onMediaPlayerClickEvent(int position);
}

在您的CustomArrayAdapter中添加一个constructor,如下所示:

public CustomArrayAdapter(Context context, PlayerCallBack playerCallBack, ArrayList<CustomWord> customWords) {
        this.context = context;
        this.playerCallBack = playerCallBack;
        this.customWords = customWords;
    }

ImageView点击监听器的代码更改为此:

 playIconSecondLanguageImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playerCallBack.onMediaPlayerClickEvent(position);
            }
        });

在您的NumbersActivity中:

 CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(customWords, getApplicationContext(), new PlayerCallBack() {
            @Override
            public void onMediaPlayerClickEvent(int position) {
                mMediaPlayer = MediaPlayer.create(v.getContext(), customWord.getmSecondLanguageSoundId());
                mMediaPlayer.start();
            }
        });

没有,您可以随意玩MediaPlayer

答案 2 :(得分:0)

谷歌搜索后,我找到了解决方案。 声音源正在NumbersActivity.java类中设置为Activity的“ CustomArrayAdapter.java”类中播放。点击图片播放声音后,声音正在播放,点击“ Home”移动按钮,激活“ Activity:NumbersActivity”,进入 onPause然后是onStop状态。但声音正在播放。 一种方法是单击“主页”按钮时查找在后台运行的进程。 那是“ com.example.customarrayadapter”,所以我可以找到该进程并通过其ID杀死它: 代码写在“活动:NumbersActivity”中

 } //End Of Oncreate

  protected void onStop() {
        super.onStop();
        ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> services = manager.getRunningAppProcesses();
        String service1name = services.get(0).processName;
        int processPid = services.get(0).pid;
        Log.d("*Process PID*","**********");
        Log.d(activityNameString,"onStop invoked");
        Log.d(activityNameString,"Process Id is : "+service1name+"\n");
        android.os.Process.killProcess(processPid);

    }
}//End of NumbersActivity class