0

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

当我创建 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);
              }
              };
              };
4

1 回答 1

2

这不是语法问题;这是一个变量初始化问题。要么 要么myServicemyService.playernull该行在中执行时onCreate()。检查你的代码,看看你在哪里初始化它们,并确保在设置它们之前你没有引用它们。

于 2011-03-18T08:23:15.913 回答