如何在Android中正确停止媒体播放器启动和停止媒体播放器?

时间:2017-09-13 05:54:31

标签: android android-asynctask android-mediaplayer streaming-radio

我正在尝试在打开我的应用程序时流式传输在线广播,当我第一次缓慢运行时我关闭应用程序,然后再次启动播放器从播放器上次关闭的位置播放,然后在播放结束后停止播放我必须手动启动以流式传输当前广播级别的网址

我的编码:

public class MainActivity extends AppCompatActivity {

    DrawerLayout drawer;
    ImageView list_activity_check;
    ImageView share,speaker,mute, control;
    DrawerListAdapter drawerListAdapter;
    ListView listview_nav;

    private SmallBang mSmallBang;

    String [] Items={"Program Lists","Rate app"} ;
    int [] images={R.drawable.pro_logo,
            R.drawable.rate_icon} ;


    String[] titles = {
            "Ippadikku Idhayam",
            "Akilam 360",
            "Cine Pattarai",
            "Palsuvai Thoranam",
            "Pesum Noolagam",
            "Lollu Cafe",
            "Kavi Saagaram",
            "Aa muthal Akk",
            "Thiraicholai",
            "Kathamba Saaral",
            "Paarkatha Pakkangal",
            "Pagadi Panna Porom",

    };

    public static  final String[] fromtime = new String[]{"10:30 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};

    public static  final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};



    Integer[] images0 = {
            R.drawable.ipadikku_idhayam,
            R.drawable.akilam_360,
            R.drawable.cine_pattarai,
            R.drawable.palsuvai_thoranam,
            R.drawable.pesum_noolagam,
            R.drawable.lollu_cafe,
            R.drawable.kavi_saagaram,
            R.drawable.aa_muthal_akk,
            R.drawable.thiraicholai,
            R.drawable.kathamba_saaral,
            R.drawable.paarkatha_pakkangal,
            R.drawable.pagadi_panna_porom,

    };

//************* Current Show ***************//

    ListView list,lvshow;
    List<Program> rowItems;
    int  iImageId;
    String sTitle,sFrom,sTo ;
    SQLiteDatabase db;
    ImageView music;
    int media1;
    int intValue1;
    AdapAdapter Adapadapter;
    ArrayList<String> iTitle = null;
    ArrayList<String> sQuantity = null;
    ArrayList<String> sQuantity1 = null;
    ArrayList<String> sImageID = null;



//***************************************//


    SeekBar seekbar;
    AudioManager audioManager;
    MediaPlayer media, mediaPlayer;
boolean playPause = false;
    boolean intialStage = true;
    int intvalue  ;

    ImageView timer;

    private static final int NOTIFICATION_ID = 1;
    String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addNotification();
        mSmallBang = SmallBang.attach2Window(this);

        list_activity_check = (ImageView) findViewById(R.id.list_view);
        share = (ImageView) findViewById(R.id.share);
        speaker = (ImageView) findViewById(R.id.speaker);
        mute = (ImageView) findViewById(R.id.mute);
        control = (ImageView) findViewById(R.id.play);
        timer = (ImageView) findViewById(R.id.timer);

        //************ Current show ************//


        db = this.openOrCreateDatabase("MukilApp",Context.MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");

        rowItems = new ArrayList<Program>();
        for (int i = 0; i < titles.length; i++) {
            Program item = new Program(images0[i], titles[i],fromtime[i],totime[i]);
            rowItems.add(item);
        }
        db.execSQL("DELETE FROM proname;");

        lvshow = (ListView) findViewById(R.id.lvshow);

        // listView.setVisibility(View.INVISIBLE);
        final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
        for (int i = 0; i < adapter.getCount(); i++) {
            Program rowItem = (Program) adapter.getItem(i);

            iImageId = rowItem.getImageId();
            sTitle = rowItem.getTitle();
            sFrom = rowItem.getFromtime();
            sTo = rowItem.getTotime();

            db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");

        }


        final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
                "AND ToTiming >= time('now', 'localtime')\n", null);
        if (cView.getCount() > 0) {

            sImageID = new ArrayList<String>();
            iTitle = new ArrayList<String>();
            sQuantity = new ArrayList<String>();
            sQuantity1 = new ArrayList<String>();

            while (cView.moveToNext()) {

                sImageID.add(cView.getString(1));
                iTitle.add(cView.getString(2));
                sQuantity.add(cView.getString(3));
                sQuantity1.add(cView.getString(4));

                Adapadapter = new AdapAdapter(this, sImageID, iTitle, sQuantity, sQuantity1);
                lvshow.setAdapter(Adapadapter);
            }

        }


        //*************************************//



        timer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSmallBang.bang(v);
                mSmallBang.setmListener(new SmallBangListener() {
                    @Override
                    public void onAnimationStart() {

                    }

                    @Override
                    public void onAnimationEnd() {

                        Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);

                        Bundle bndlanimation =
                                ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
//                        startActivity(slideactivity, bndlanimation);
                        startActivityForResult(slideactivity, 1001,bndlanimation);
//                finish();
                    }
                });
            }
        });

    media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
        media.start();
        media.setLooping(true);
        mediaPlayer = new MediaPlayer();

        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        if (intialStage) {
            new Player()
                    .execute(URL);
        }



        intvalue = mediaPlayer.getAudioSessionId();
        control.setBackgroundResource(R.drawable.pause);

        control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (playPause == false) {
                    control.setBackgroundResource(R.drawable.play);
                    mediaPlayer.stop();
                    new Player().cancel(true);
                    media.stop();
                    media.reset();
                    mediaPlayer.reset();
                    if (mediaPlayer.isPlaying())
                        mediaPlayer.stop();
                    mediaPlayer.reset();
                    media.stop();

                    playPause = true;
                } else {
                    control.setBackgroundResource(R.drawable.pause);
                    if (intialStage) {
                        new Player()
                                .execute(URL);
                    } else {
                        if (!mediaPlayer.isPlaying())
                            mediaPlayer.start();
                    }
                    playPause = false;
                }

            }
        });

        speaker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speaker.setVisibility(View.INVISIBLE);
                mute.setVisibility(View.VISIBLE);
                media.setVolume(0, 0);
                mediaPlayer.setVolume(0, 0);

                speaker.setImageResource(R.drawable.speaker);
                mSmallBang.bang(v);
                mSmallBang.setmListener(new SmallBangListener() {
                    @Override
                    public void onAnimationStart() {

                    }

                    @Override
                    public void onAnimationEnd() {

                    }


                });

            }
        });
        mute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                speaker.setVisibility(View.VISIBLE);
                mute.setVisibility(View.INVISIBLE);
                media.setVolume(1, 1);
                mediaPlayer.setVolume(1, 1);

            }
        });


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title

        }


        try {
            seekbar = (SeekBar) findViewById(R.id.seekbar1);

            audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            seekbar.setMax(audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
            seekbar.setProgress(audioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC));



            seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onStopTrackingTouch(SeekBar arg0) {
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0) {
                }

                @Override
                public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                            progress, 0);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


        listview_nav = (ListView) findViewById(R.id.listview_nav);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();


        drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
        listview_nav.setAdapter(drawerListAdapter);

        listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position == 0){

                    Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
                    startActivity(in);

                }else if(position == 1){

                }
            }


        });



        list_activity_check.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {


                list_activity_check.setImageResource(R.drawable.playlist);
                mSmallBang.bang(v);
                mSmallBang.setmListener(new SmallBangListener() {
                    @Override
                    public void onAnimationStart() {

                    }

                    @Override
                    public void onAnimationEnd() {


                        Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
                        slideactivity.putExtra("sessionvalue", intvalue);

                        Bundle bndlanimation =
                                ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
                        startActivity(slideactivity, bndlanimation);

                    }
                });

            }


        });


        share.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {


                share.setImageResource(R.drawable.share_icon);
                mSmallBang.bang(v);
                mSmallBang.setmListener(new SmallBangListener() {
                    @Override
                    public void onAnimationStart() {

                    }

                    @Override
                    public void onAnimationEnd() {

                    }


                });

                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
                startActivity(Intent.createChooser(sharingIntent, "Share via"));

            }
        });

        PhoneStateListener phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_RINGING) {
                    //INCOMING call
                    //do all necessary action to pause the audio
                    if(mediaPlayer!=null){//check mp

                        if(mediaPlayer.isPlaying()){

                            mediaPlayer.pause();
                        }
                    }

                    if(media!=null){//check mp

                        if(media.isPlaying()){

                            media.pause();
                        }
                    }



                } else if(state == TelephonyManager.CALL_STATE_IDLE) {
                    //Not IN CALL
                    //do anything if the phone-state is idle

                    if(mediaPlayer == null){//check mp

                        if(!mediaPlayer.isPlaying()) {

                            mediaPlayer.start();
                        }
                    }
                    if(media==null){//check mp

                        if(!media.isPlaying()){

                            media.start();
                        }
                    }



                } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
                    //A call is dialing, active or on hold
                    //do all necessary action to pause the audio
                    //do something here
                    if(mediaPlayer!=null){//check mp

                        if(mediaPlayer.isPlaying()){

                            mediaPlayer.pause();
                        }
                    }
                    if(media!=null){//check mp

                        if(media.isPlaying()){

                            media.pause();
                        }
                    }



                }
                super.onCallStateChanged(state, incomingNumber);
            }
        };//end PhoneStateListener


        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if(mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }


    }



    private void addNotification() {
        NotificationCompat.Builder builder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.mukil)
                        .setContentTitle("MUKIL FM")
                        .setContentText("Smartah Kelunga Ungal MukilFm");

        // Add as notification
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
    }

    class Player extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog progress;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            Boolean prepared;
            try {

                mediaPlayer.setDataSource(params[0]);
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // TODO Auto-generated method stub
                        intialStage = true;
                        playPause = false;
                        control.setBackgroundResource(R.drawable.play);
                        mediaPlayer.stop();
                        mediaPlayer.reset();

                    }
                });
                mediaPlayer.prepare();
                mediaPlayer.prepareAsync();
                prepared = true;
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                Log.d("IllegarArgument", e.getMessage());
                prepared = false;
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                prepared = false;
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                prepared = false;
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                prepared = false;
                e.printStackTrace();
            }
            return prepared;
        }
        @Override
        protected void onPostExecute(Boolean result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (progress.isShowing()) {
                progress.cancel();
            }
            Log.d("Prepared", "//" + result);
            mediaPlayer.start();
            media.stop();

            intialStage = false;
        }

        public Player() {
            progress = new ProgressDialog(MainActivity.this);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            this.progress.setMessage("Buffering...");
            media.start();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 1001) {

                String result=data.getStringExtra("result");

                if(result.equalsIgnoreCase("STOP")){

                onStop();
                    finish();


            }else if(result.equalsIgnoreCase("Do Nothing")){


                    Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();

                }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if(media != null){
//            media.stop();  //Stops playback after playback has been stopped or paused
            media.release(); //Releases resources associated with this MediaPlayer object
            media = null;
        }
        if(mediaPlayer!= null){
//            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer= null;
        }
    }

    public void onBackPressed() {

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {


        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Exit");

        // set dialog message
        alertDialogBuilder
                .setMessage("Do you really want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {

                        MainActivity.this.finish();

                        mediaPlayer.release();
                        media.release();

                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {

                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
//        super.onBackPressed();
    }

}

请帮我解决这个问题.. 提前谢谢..

1 个答案:

答案 0 :(得分:0)

在活动的onStop()中停止并释放媒体播放器。

将以下代码放入 onStop()

@Override
public void onStop() {
    super.onStop();
    if(media != null){
      media.stop();  //Stops playback after playback has been stopped or paused
      media.release(); //Releases resources associated with this MediaPlayer object
      media = null;
    }
    if(mediaPlayer!= null){
      mediaPlayer.stop();
      mediaPlayer.release();
      mediaPlayer= null;
    }
}

这是阻止媒体播放器的正确方法。

希望有所帮助:)