Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Can';无法在onCreate中获取歌曲持续时间,但可以在按下按钮时获取_Android_Media Player_Android Context - Fatal编程技术网

Android Can';无法在onCreate中获取歌曲持续时间,但可以在按下按钮时获取

Android Can';无法在onCreate中获取歌曲持续时间,但可以在按下按钮时获取,android,media-player,android-context,Android,Media Player,Android Context,我有一个自定义媒体服务和一个音频播放器类,它与之通信,但不绑定到该服务 当我创建MyService的对象并编写代码时:- myService.player.getDuration()在onCreate中,我在这一行得到了空指针异常 但是,如果我在同一屏幕上单击某个按钮侦听器时编写此代码,则会得到确切的持续时间 我已经尝试了所有可能的语法来解决这个问题,但是我仍然无法解决这个问题 **我的服务代码是:-** private static final String TAG = "MyServ

我有一个自定义媒体服务和一个音频播放器类,它与之通信,但不绑定到该服务

当我创建MyService的对象并编写代码时:-
myService.player.getDuration()
onCreate
中,我在这一行得到了空指针异常

但是,如果我在同一屏幕上单击某个按钮侦听器时编写此代码,则会得到确切的持续时间

我已经尝试了所有可能的语法来解决这个问题,但是我仍然无法解决这个问题

**我的服务代码是:-**

    private static final String TAG = "MyService";
    public static MediaPlayer player;
    String song_uri,url;
    Bundle b;
    private IBinder myBinder;
    private boolean isplaying;
    public static final String Song_uri="song_uri";
    public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";

        @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public class MyBinder extends Binder{
        MyService getService()
        {
            return MyService.this;
        }
    }   

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate "+song_uri);
            }   


    @Override
    public void onDestroy() {
        //Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        DataManager.getInstance().setWantsToPlaySong(false);
        DataManager.getInstance().setCurrentPosition(0);
        Log.d(TAG, "onDestroy");
        player.stop();
    //player.release();
    }

public void onPause()
{

player.pause();
}

public double duration()
{
return player.getDuration();    
}

    public void onStart(Intent intent, int startid) {
        DataManager.getInstance().setWantsToPlaySong(true);
    Bundle b=intent.getExtras();
    song_uri=b.getString("song_uri");
    Uri path=Uri.parse(song_uri);


    player = MediaPlayer.create(this,path );
    player.setLooping(false); // Set looping
    //Toast.makeText(this, "My Service Started"+" Duration = "+(player.getDuration()/1000)/60, Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onStart"+song_uri);
        player.start();
    }
音频播放器的代码为:-

 uri = this.getIntent().getExtras().getString("song_uri");
        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);
        buttonPause = (Button) findViewById(R.id.buttonPause);
        tracks = dbManager.getAllSongs(AudioPlayer2.this);

        buttonForward = (Button) findViewById(R.id.buttonforward);
        buttonBackward = (Button) findViewById(R.id.buttonbackward);
        //=========================================================================================
        sArtworkUri = Uri.parse("content://media/external/audio/albumart");
          //myservice=new MyService();

        Uri path = Uri.parse(uri);
        current_song=this.getIntent().getExtras().getInt("current_song");
        albumArtUri = this.getIntent().getExtras().getString("album_art");
        Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
         album_id = Long.parseLong(this.getIntent().getStringExtra("album_id"));
        int id = Integer.parseInt(this.getIntent().getStringExtra("album_id"));

        albumImageUri = ContentUris.withAppendedId(sArtworkUri, album_id);
        ivAlbumArt = (ImageView) findViewById(R.id.album_art);

        songName = this.getIntent().getStringExtra("song_name");
        albumName = this.getIntent().getStringExtra("album_name");

        tvName = (TextView) findViewById(R.id.tv_name);
        tvAlbum = (TextView) findViewById(R.id.tv_album);
        if (songName != null) {
            tvName.setText(songName);
        }

        if (albumName != null) {
            tvAlbum.setText(albumName);
        }

    //  buttonStart.performClick();

        if (DataManager.getInstance().getOnPausedSong()=="y"){
            //Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
            if(DataManager.getInstance().getPausedSongName()==songName){
                //Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
            buttonStart.setVisibility(View.GONE);
            buttonPause.setVisibility(View.VISIBLE);
        }
        }
        FetchImage fetchImage = new FetchImage();
        fetchImage.execute();

          /*if(DataManager.getInstance().getSong_uri()!=null)
          {
              stopService(new Intent(this, MyService.class));
          }*/
    //  if(myService.player.isPlaying())
        //{
         stopService(new Intent(this, MyService.class));
         Intent intent = new Intent(this,MyService.class);
            Bundle b = new Bundle();
            b.putString("song_uri",uri );
            intent.putExtras(b);
            startService(intent);
            myService.player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    buttonStart.setVisibility(View.VISIBLE);
                    buttonPause.setVisibility(View.GONE);
                }
            });
            buttonStart.setVisibility(View.GONE);
            buttonPause.setVisibility(View.VISIBLE);

            //  Toast.makeText(this, "Duration: "+myService.player.getDuration(), Toast.LENGTH_LONG).show();
         /*//}//DataManager.getInstance().setSong_uri(uri); 
        Intent intent = new Intent(this,MyService.class);
        Bundle b = new Bundle();
        b.putString("song_uri",uri );
        intent.putExtras(b);
        startService(intent);
        buttonStart.setVisibility(View.GONE);
        buttonPause.setVisibility(View.VISIBLE);
        DataManager.getInstance().setSong_uri(uri);
        DataManager.getInstance().setOnPausedSong("y");
        DataManager.getInstance().setPausedSongName(songName);
        */  //buttonStart.setPressed(true);

        //=======================================================================================
        buttonStart.setOnClickListener(this);
        buttonPause.setOnClickListener(this);
        buttonForward.setOnClickListener(this);
        buttonBackward.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
      // buttonPause.performClick();
/*        new Thread(myThread).start();

*/    }

      // Thread for seekbar


        // song starts playing

      public void onClick(View src) {
        switch (src.getId()) {
        case R.id.buttonStart:
            if(DataManager.getInstance().getSongPause()=="y"){
                myService.player.start();
                DataManager.getInstance().setSongPause("n");
                buttonStart.setVisibility(View.GONE);
                buttonPause.setVisibility(View.VISIBLE);
            //  DataManager.getInstance().setWantsToPlaySong(true);
                //DataManager.getInstance().setOnPausedSong("n");
                //DataManager.getInstance().setOnPausedSong("y");
            }else{
        stopService(new Intent(this, MyService.class));
            DataManager.getInstance().setSong_uri(uri); 
            Intent intent = new Intent(this,MyService.class);
            Bundle b = new Bundle();
            b.putString("song_uri",uri );
            intent.putExtras(b);
            startService(intent);
            buttonStart.setVisibility(View.GONE);
            buttonPause.setVisibility(View.VISIBLE);
            DataManager.getInstance().setOnPausedSong("y");
            DataManager.getInstance().setPausedSongName(songName);
            }
            //Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
            break;
        case R.id.buttonStop:
          Log.d(TAG, "onClick: stopping srvice");
          stopService(new Intent(this, MyService.class));
          buttonStart.setVisibility(View.VISIBLE);
            buttonPause.setVisibility(View.GONE);
     break;
        case R.id.buttonforward:
             stopService(new Intent(this, MyService.class));
             current_song++;
            FetchAllMusic fetchAllMusic = new FetchAllMusic();
            fetchAllMusic.execute();
            //new Thread(myThread).start();


                break;
        case R.id.buttonbackward:
              Log.d(TAG, "onClick: stopping service");
              stopService(new Intent(this, MyService.class));
              if(current_song>0){   
              current_song--;
               }
                FetchAllMusic fetchAllMusic2 = new FetchAllMusic();
                fetchAllMusic2.execute();

              break;
        case R.id.buttonPause:
              buttonStart.setVisibility(View.VISIBLE);
                buttonPause.setVisibility(View.GONE);
            /* MyService myservice=new MyService();
             myservice.onPause();*/
                myService.player.pause();
                DataManager.getInstance().setSongPause("y");
                DataManager.getInstance().setWantsToPlaySong(false);
                DataManager.getInstance().setOnPausedSong("n");
                DataManager.getInstance().setPausedSongName(songName);
                //duration=myService.player.getDuration();

            //   Toast.makeText(this, ""+duration, Toast.LENGTH_LONG).show();

        }
      }
        public void onBackPressed() {
            try {
                    //addvideo.removeView(DBManager.getInstance().getVideo());
                DataManager.getInstance().setSong_uri(uri);
            DataManager.getInstance().setAlbum_id(""+album_id);
            DataManager.getInstance().setAlbumName(albumName);
            DataManager.getInstance().setSongName(songName);
            DataManager.getInstance().setAlbumArtUri(albumArtUri);
            DataManager.getInstance().setCurrent_song(current_song);
            DataManager.getInstance().setWantsToPlaySong(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onBackPressed();
        }

          private Runnable myThread = new Runnable(){

              @Override
              public void run() {
                      Log.d(TAG, "Thread Starts");
              // TODO Auto-generated method stub
              while (myProgress<100){
              try{
                      Log.d(TAG, "Thread Starts");
                      myHandle.sendMessage(myHandle.obtainMessage());
              Thread.sleep(3000);
              }
              catch(Throwable t){
              }
              }
              }

              Handler myHandle = new Handler(){

              public void handleMessage(Message msg) {
              // TODO Auto-generated method stub
              myProgress++;
              seekbar.setProgress(myProgress);
              }
              };
              };
uri=this.getIntent().getExtras().getString(“歌曲uri”);
buttonStart=(按钮)findViewById(R.id.buttonStart);
buttonStop=(按钮)findViewById(R.id.buttonStop);
buttonPause=(按钮)findViewById(R.id.buttonPause);
tracks=dbManager.getAllSongs(AudioPlayer2.this);
buttonForward=(按钮)findViewById(R.id.buttonForward);
buttonBackward=(按钮)findViewById(R.id.buttonBackward);
//=========================================================================================
sArtworkUri=Uri.parse(“content://media/external/audio/albumart");
//myservice=newmyservice();
uripath=Uri.parse(Uri);
当前歌曲=this.getIntent().getExtras().getInt(“当前歌曲”);
albumArtUri=this.getIntent().getExtras().getString(“album_艺术”);
Uri sArtworkUri=Uri.parse(“content://media/external/audio/albumart");
album_id=Long.parseLong(this.getIntent().getStringExtra(“album_id”);
int id=Integer.parseInt(this.getIntent().getStringExtra(“album_id”);
albumImageUri=ContentUris.withAppendedId(sArtworkUri,album_id);
ivAlbumArt=(ImageView)findViewById(R.id.album_艺术);
songName=this.getIntent().getStringExtra(“歌曲名称”);
albumName=this.getIntent().getStringExtra(“album_name”);
tvName=(TextView)findViewById(R.id.tv_name);
tvAlbum=(TextView)findViewById(R.id.tv_相册);
if(songName!=null){
tvName.setText(songName);
}
if(albumName!=null){
tvAlbum.setText(albumName);
}
//buttonStart.performClick();
如果(DataManager.getInstance().getOnPausedSong()=“y”){
//Toast.makeText(AudioPlayer2.this,“stage 1”,Toast.LENGTH_SHORT.show();
如果(DataManager.getInstance().getPausedSongName()==songName){
//Toast.makeText(AudioPlayer2.this,“stage 1”,Toast.LENGTH_SHORT.show();
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
}
}
FetchImage FetchImage=新建FetchImage();
fetchImage.execute();
/*if(DataManager.getInstance().getSong_uri()!=null)
{
stopService(newintent(this,MyService.class));
}*/
//if(myService.player.isPlaying())
//{
stopService(newintent(this,MyService.class));
Intent Intent=新的Intent(这个,MyService.class);
Bundle b=新Bundle();
b、 putString(“song_uri”,uri);
意向.附加条款(b);
startService(意向);
myService.player.setOnCompletionListener(新的OnCompletionListener(){
@凌驾
完成时的公共作废(MediaPlayer mp){
//TODO自动生成的方法存根
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
}
});
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
//Toast.makeText(这个,“Duration:+myService.player.getDuration(),Toast.LENGTH\u LONG.show();
/*//}//DataManager.getInstance().setSong_uri(uri);
Intent Intent=新的Intent(这个,MyService.class);
Bundle b=新Bundle();
b、 putString(“song_uri”,uri);
意向.附加条款(b);
startService(意向);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setOnPausedSong(“y”);
DataManager.getInstance().setPausedSongName(songName);
*///buttonStart.setPressed(true);
//=======================================================================================
buttonStart.setOnClickListener(此);
buttonPause.setOnClickListener(此);
buttonForward.setOnClickListener(此);
buttonBackward.setOnClickListener(此);
buttonStop.setOnClickListener(此);
//buttonPause.performClick();
/*新线程(myThread.start();
*/    }
//seekbar螺纹
//歌曲开始播放
公共void onClick(视图src){
开关(src.getId()){
案例R.id.buttonStart:
如果(DataManager.getInstance().getSongPause()=“y”){
myService.player.start();
DataManager.getInstance().setSongPause(“n”);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
//DataManager.getInstance().setWantsToPlaySong(true);
//DataManager.getInstance().setOnPausedSong(“n”);
//DataManager.getInstance().setOnPausedSong(“y”);
}否则{
stopService(newintent(this,MyService.class));
DataManager.getInstance().setSong_uri(uri);
Intent Intent=新的Intent(这个,MyService.class);
Bundle b=新Bundle();
b、 putString(“song_uri”,uri);
意向.附加条款(b);
startService(意向);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getIn