音乐(活动)重新启动旋转设备时......为什么会发生?以及如何我可以重新启动停止吗? [英] Music(activity) restarts when rotating device...why does it happen?and how can i stop it from restarting?

查看:137
本文介绍了音乐(活动)重新启动旋转设备时......为什么会发生?以及如何我可以重新启动停止吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我想我的问题介绍了自己, 反正这里是code

 公共类NowPlaying扩展活动实现Serializable {
    静态MediaPlayer的熔点为新的MediaPlayer();

    字符串的艺术家; ProgressDialog PD;
    INT位置;字符串键= NULL;
    / * INT Z = 0;
    搜索栏songProgressBar;
    TextView的songCurrentDurationLabel;
    TextView的songTotalDurationLabel;
    私人处理程序mHandler =新的处理程序();
    私营公用事业utils的=新的应用程序();
    * /

    @燮pressLint(NewApi)
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.now_playing);
        意图I = getIntent();
         位置= i.getIntExtra(数据2,0);
         / * songProgressBar =(搜索栏)findViewById(R.id.songProgressBar);
          songCurrentDurationLabel =(TextView中)findViewById(R.id.songCurrentDurationLabel);
          songTotalDurationLabel =(TextView中)findViewById(R.id.songTotalDurationLabel);
            * /

        最后的ArrayList< SongDetails>歌曲= getIntent()getParcelableArrayListExtra(数据1)。

         PD =新ProgressDialog(本);
         pd.setMessage(载入中...);


            Playservice(听歌,位置);


        按钮bfake =(按钮)findViewById(R.id.bFake);
        的LinearLayout LL =(的LinearLayout)findViewById(R.id.LL);
        按钮暂停=(按钮)findViewById(R.id.bPlayPause);
        // songProgressBar.setOnSeekBarChangeListener((OnSeekBarChangeListener)本); // 重要

        mp.setOnCompletionListener(新MediaPlayer.OnCompletionListener(){
            @覆盖
            公共无效onCompletion(MediaPlayer的播放器){

                位置=位置+ 1;



                 Playservice(听歌,位置);





            }});
         bfake.setOnTouchListener(新OnSwipeTouchListener()
         {公共无效onSwipeRight(){
                 位置=位置1;
                 Playservice(听歌,位置);
             }
                公共无效onSwipeLeft(){
                 位置=位置+ 1;
                 Playservice(听歌,位置);
                }
                公共无效onSwipeBottom(){
                    mp.stop();
                }
               });
            LL.setOnTouchListener(新OnSwipeTouchListener(){
               公共无效onSwipeBottom(){
                    mp.stop();
                }
               });
            Pause.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v)
            {如果(mp.isPlaying())
                mp.pause();
            其他
                mp.start();
            }
            });
    }

     私人无效Playservice(ArrayList中< SongDetails>的歌曲,诠释的位置)

         {



         INT currentPosition = 0;
            INT总= mp.getDuration();
           / *而(MP =空&放大器;!&安培; currentPosition<总){
                尝试 {
                    视频下载(1000);
                    currentPosition = mp.getCurrentPosition();
                }赶上(InterruptedException异常E){
                    打破;
                }赶上(例外五){
                    打破;
                }
          // songProgressBar.setProgress(currentPosition);
            * /





          尝试 {
                 字符串AB = songs.get(位置).getPath2()的toString()。
                 艺术家= songs.get(位置).getArtist();
                 新XMLPARSE()执行()。
                如果(mp.isPlaying())
                    {mp.stop();
                        }
                    mp.reset();
                    mp.setDataSource(AB);
                    MP prepare()。
                    mp.start();
            // songProgressBar.setProgress(0);
                // songProgressBar.setMax(mp.getDuration());
                    新的主题()启动();
                }赶上(抛出:IllegalArgumentException E){

                    e.printStackTrace();
                }赶上(SecurityException异常E){
                    e.printStackTrace();
                }赶上(IllegalStateException异常E){
                    e.printStackTrace();
                }赶上(IOException异常E)
                {
                    e.printStackTrace();
                }


         }
     / *公共无效onStartTrackingTouch(搜索栏搜索栏){
        }

        公共无效onStopTrackingTouch(搜索栏搜索栏){
        }

        公共无效onProgressChanged(搜索栏搜索栏,INT进步,
                布尔FROMUSER){
            如果(FROMUSER)mp.seekTo(进度);

        }


* /
一流的XMLPARSE扩展的AsyncTask<太虚,可绘制,绘制对象>
 {
    保护无效onPostExecute(可绘制的结果){
       // super.onPostExecute(结果);
        pd.dismiss();
        的LinearLayout LL =(的LinearLayout)findViewById(R.id.LL);
         LL.setBackgroundDrawable(结果);


        // Toast.makeText(getApplicationContext(),结果,1000).show();
    }

    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pd.show();
    }
    @覆盖
    受保护的可绘制doInBackground(空... PARAMS){
        可绘制S =的getData();
        返回S;
    }

    公众可绘制对象的getData()
    {绘制对象绘制= NULL; // =新BitmapDrawable(BMP);

        艺术家= artist.trim();
        艺术家= artist.replace(,20%);

        尝试{

          网址URL =新的URL(http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=+艺术家+&放大器; API_KEY = 1732077d6772048ccc671c754061cb18);
        URLConnection的连接= url.openConnection();
        DocumentBuilderFactory的DBF = DocumentBuilderFactory.newInstance();
        DocumentBuilder的DB = dbf.newDocumentBuilder();

        最终的文档文件= db.parse(connection.getInputStream());
        document.getDocumentElement()归()。
        的XPathFactory的XPathFactory = XPathFactory.newInstance();
        的XPath xPathEvaluator = xPathfactory.newXPath();
        XPathEx pression nameExpr = xPathEvaluator.compile(// LFM /艺术家/图像);
        // XPathEx pression nameExpr = xPathEvaluator.compile(// LFM /曲目/音轨/图像);
        NodeList的NL =(节点列表)nameExpr.evaluate(文件,XPathConstants.NODESET);


        对于(INT ZZZ = 0; ZZZ< nl.getLength(); ZZZ ++)
        {
            节点currentItem = nl.item(ZZZ);
            键= currentItem.getTextContent();


            //键= currentItem.getAttributes()getNamedItem(URI)getNodeValue()。
        } URL ulrn =新的URL(键);
        HttpURLConnection的CON =(HttpURLConnection类)ulrn.openConnection();
        InputStream的是= con.getInputStream();
        BMP位= BitmapFactory.de codeStream(是);
        绘制=新BitmapDrawable(BMP);
        }
        赶上(例外五)
        {}
        返回绘制;}
  }}
 

解决方案

它重新启动,因为你的活动被再创造......每当用户更改设备的onCreate方法被再次调用的方向。要解决这个问题尝试添加到您的活动清单文件:

 安卓configChanges =方向| keyboardHidden>
 

well i think my question describes itself , anyways here is the code

public class  NowPlaying extends Activity implements Serializable  {
    static MediaPlayer mp =new MediaPlayer();

    String artist;ProgressDialog pd;
    int position; String key=null ;
    /*int z=0;
    SeekBar songProgressBar ;
    TextView songCurrentDurationLabel;
    TextView songTotalDurationLabel ;
    private Handler mHandler = new Handler();
    private Utilities utils=new Utilities();
    */

    @SuppressLint("NewApi")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.now_playing);
        Intent i = getIntent();
         position=i.getIntExtra("Data2", 0);
         /* songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
          songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
          songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
            */

        final ArrayList<SongDetails> songs = getIntent().getParcelableArrayListExtra("Data1"); 

         pd = new ProgressDialog(this);
         pd.setMessage("Loading...");


            Playservice(songs,position  );


        Button bfake=(Button) findViewById(R.id.bFake);
        LinearLayout LL=(LinearLayout) findViewById(R.id.LL);
        Button Pause=(Button)findViewById(R.id.bPlayPause);
        // songProgressBar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this); // Important

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer player) {

                position=position+1;



                 Playservice(songs,position);





            }});
         bfake.setOnTouchListener(new OnSwipeTouchListener()
         {           public void onSwipeRight() {
                 position=position-1;   
                 Playservice(songs,position  );
             }
                public void onSwipeLeft() {
                 position=position+1;   
                 Playservice(songs,position );
                }
                public void onSwipeBottom() {
                    mp.stop();
                }
               });
            LL.setOnTouchListener(new OnSwipeTouchListener() {
               public void onSwipeBottom() {
                    mp.stop();
                }
               });  
            Pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
            {if(mp.isPlaying())
                mp.pause();
            else
                mp.start();
            }
            });
    }

     private void Playservice( ArrayList<SongDetails> songs, int position    )

         {



         int currentPosition= 0;
            int total = mp.getDuration();
           /* while (mp!=null && currentPosition<total) {
                try {
                    Thread.sleep(1000);
                    currentPosition= mp.getCurrentPosition();
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    break;
                }            
          //      songProgressBar.setProgress(currentPosition);
            */





          try {
                 String ab=songs.get(position).getPath2().toString();
                 artist=songs.get(position).getArtist();
                 new Xmlparse().execute(); 
                if(mp.isPlaying())
                    {   mp.stop();
                        }
                    mp.reset();
                    mp.setDataSource(ab) ;
                    mp.prepare();
                    mp.start();
            //      songProgressBar.setProgress(0);
                //  songProgressBar.setMax(mp.getDuration());
                    new Thread().start();
                } catch (IllegalArgumentException e) {

                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e)
                {
                    e.printStackTrace();
                } 


         }
     /*public void onStartTrackingTouch(SeekBar seekBar) {
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
        }

        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            if(fromUser) mp.seekTo(progress);

        }


*/
class Xmlparse extends AsyncTask<Void,Drawable,Drawable>
 {
    protected void onPostExecute(Drawable result) {
       // super.onPostExecute(result);
        pd.dismiss();
        LinearLayout LL=(LinearLayout) findViewById(R.id.LL);
         LL.setBackgroundDrawable(result);


        // Toast.makeText(getApplicationContext(),result, 1000).show();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd.show();
    }
    @Override
    protected Drawable doInBackground(Void... params) {
        Drawable s =getData();
        return s;
    }  

    public Drawable getData()
    {  Drawable drawable = null;//=new BitmapDrawable(bmp); 

        artist=artist.trim();
        artist=artist.replace(" ", "%20");

        try{

          URL url = new URL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" +artist+              "&api_key=1732077d6772048ccc671c754061cb18");
        URLConnection connection = url.openConnection();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        final Document document = db.parse(connection.getInputStream());
        document.getDocumentElement().normalize();
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xPathEvaluator = xPathfactory.newXPath();
        XPathExpression nameExpr = xPathEvaluator.compile("//lfm/artist/image");
        // XPathExpression nameExpr = xPathEvaluator.compile("//lfm/tracks/track/image");
        NodeList nl = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);


        for (int zzz = 0; zzz < nl.getLength(); zzz++)
        {
            Node currentItem = nl.item(zzz);
            key = currentItem.getTextContent();


            // key = currentItem.getAttributes().getNamedItem("uri").getNodeValue();
        }URL ulrn = new URL(key);
        HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
        InputStream is = con.getInputStream();
        Bitmap bmp = BitmapFactory.decodeStream(is);
        drawable=new BitmapDrawable(bmp); 
        }
        catch(Exception e)
        {}
        return drawable;}   
  }}

解决方案

it restarts because your activity was recreated... each time the user change the orientation of the device the oncreate method is called again. to fix this try add this to your activity in the manifest file:

   android:configChanges="orientation|keyboardHidden">

这篇关于音乐(活动)重新启动旋转设备时......为什么会发生?以及如何我可以重新启动停止吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆