2015-09-22 51 views
0

我有一个音乐播放器应用程序和媒体播放器所做的事情。 现在,当我打电话 PlayingService pservice = new Service(); pservice.play(file);Android服务上下文返回null

我用this的背景下,我总是喜欢Attempt to invoke virtual method java.lang.String android.content.Context.getPackageName()' on a null object reference

一个例外,我不找原因或为这个错误的解决方案!任何帮助?谢谢!

这里的活动调用pservice.play(); 在IST的onCreate():

public class PlayingActivity extends AppCompatActivity { 


public boolean serviceConnected = false; 
Bitmap songImage; 
byte[] albumart; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getWindow().setSharedElementEnterTransition(TransitionInflater.from(getApplicationContext()).inflateTransition(R.transition.seb)); 
    setContentView(R.layout.activity_playing); 


    final PlayingService pservice = new PlayingService(); 

    SeekBar seekBar = (SeekBar) findViewById(R.id.seekbar); 
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 
     @Override 
     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
      if (fromUser) { 
       pservice.seekTo(progress); 
      } 
     } 

     @Override 
     public void onStartTrackingTouch(SeekBar seekBar) { 

     } 

     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 

     } 
    }); 


    final PlayPauseView view = (PlayPauseView) findViewById(R.id.fabInfo); 
    view.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      view.toggle(); 


     } 
    }); 
    ImageView image = (ImageView) findViewById(R.id.albumArt); 
    Intent intent = getIntent(); 
    String song = intent.getExtras().getString("song"); 
    String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "Music" + File.separator + song.toString(); 
    File file = new File(path); 
    Uri uri = (Uri) Uri.fromFile(file); 
    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); 
    try { 
     mediaMetadataRetriever.setDataSource(getApplicationContext(), uri); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setTitle(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)); 
    getSupportActionBar().setSubtitle(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)); 
    toolbar.setTitleTextColor(getResources().getColor(R.color.white)); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 



    pservice.play(file); 


    try { 
     image.setImageBitmap(BitmapFactory.decodeByteArray(mediaMetadataRetriever.getEmbeddedPicture(), 0, mediaMetadataRetriever.getEmbeddedPicture().length)); 


    } catch (Exception e) { 

     e.printStackTrace(); 

     image.setImageDrawable(getDrawable(R.drawable.headset)); 


    } 


} 





@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_playing, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    if (item.getItemId() == android.R.id.home) { 
     NavUtils.navigateUpFromSameTask(this); 
    } 


    return super.onOptionsItemSelected(item); 
} 

}

这里的服务类:

public class PlayingService extends Service implements MediaPlayer.OnPreparedListener , MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener{ 

private MediaPlayer mp; 
private int currentposition; 
Context context; 



private NotificationManager nm; 
NotificationCompat.Builder builder; 

public PlayingService() { 
} 




@Override 
public IBinder onBind(Intent intent) { 


    return null; 
} 


@Override 
public boolean onUnbind(Intent intent){ 
    mp.stop(); 
    mp.release(); 
    return false; 
} 




@Override 
public void onCreate() { 
    super.onCreate(); 
    context=this; 
    currentposition=0; 
    mp=new MediaPlayer(); 
    initMediaPlayer(); 


} 




public void initMediaPlayer() { 
    mp.setOnPreparedListener(this); 
    mp.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); 
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
    mp.setOnErrorListener(this); 
    mp.setOnCompletionListener(this); 
} 



public void play(File file) { 
    currentposition=0; 


    Intent intent=new Intent(this,PlayingActivity.class); 
    PendingIntent notifyPendingIntent = 
      PendingIntent.getActivity(
        this, 
        0, 
        intent, 
        PendingIntent.FLAG_UPDATE_CURRENT 
      ); 
    PendingIntent previous=PendingIntent.getService(this, 0, new Intent(this, PlayingService.class).setAction("PREVIOUS"), 0); 
    PendingIntent pause=PendingIntent.getService(this,0,new Intent(this,PlayingService.class).setAction("PAUSE"),0); 
    PendingIntent next=PendingIntent.getService(this, 0, new Intent(this,PlayingService.class).setAction("NEXT"), 0); 

    try { 
     mp.setDataSource(this, Uri.fromFile(file)); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    builder=new NotificationCompat.Builder(this); 
    try { 
     mp.prepare(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    MediaMetadataRetriever mmr=new MediaMetadataRetriever(); 
    mmr.setDataSource(this, Uri.fromFile(file)); 


    builder.setContentIntent(notifyPendingIntent); 

    try { 
     builder.setContentTitle(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)); 
     builder.setContentText(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)); 
    }catch (Exception e) { 
     builder.setContentTitle(file.getName()); 
     builder.setContentText("unknown"); 
    } 
    builder.addAction(R.drawable.skip_previous, "Previous", previous); 
    builder.addAction(R.drawable.pause, "Pause", pause); 
    builder.addAction(R.drawable.skip_next, "Next", next); 
    builder.setStyle(new NotificationCompat.MediaStyle()); 
    try { 
     builder.setLargeIcon(BitmapFactory.decodeByteArray(mmr.getEmbeddedPicture(), 0, mmr.getEmbeddedPicture().length)); 
     Toast.makeText(this,"successfull",Toast.LENGTH_SHORT).show(); 
    }catch (Exception e) { 
     builder.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.headset)); 
     Toast.makeText(this,"not",Toast.LENGTH_SHORT).show(); 
    } 
    builder.setSmallIcon(R.drawable.ic_music_note_white_48dp); 
    builder.setColor(this.getResources().getColor(android.R.color.background_dark)); 
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify(1, builder.build()); 







} 

public void stop() { 
    if (mp.isPlaying()) { 
     mp.stop(); 
    } 


} 

public void pause() { 
    if (mp.isPlaying()) { 
     mp.pause(); 

    } 
    Toast.makeText(this,"pausing",Toast.LENGTH_SHORT 
    ).show(); 


} 

public void seekTo(int position) { 


     mp.pause(); 

    mp.seekTo(position); 
    try { 
     mp.prepare(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 


} 

public void skipForward() { 

} 

public void whilePlaying(){ 
    LayoutInflater inflater=LayoutInflater.from(this); 
    final View view= inflater.inflate(R.layout.activity_playing, null, false); 
    final SeekBar progress = (SeekBar)view.findViewById(R.id.seekbar); 


    Thread thread=new Thread(){ 
     @Override 
     public void run() { 
      while (!isInterrupted()){ 
       try { 
        Thread.sleep(1000); 

       }catch (InterruptedException ie){ 
        return; 
       } 

       progress.setMax(mp.getDuration()); 
       TextView mTextActual = (TextView) view.findViewById(R.id.textactual); 
       String actual = new SimpleDateFormat("mm:ss").format(mp.getCurrentPosition()); 
       mTextActual.setText(actual); 
       progress.setProgress(mp.getCurrentPosition()); 
      } 
     } 
    }; 
    thread.start(); 






    Toast.makeText(this,"playing",Toast.LENGTH_SHORT).show(); 



} 

public void skipBack() { 

} 

@Override 
public void onPrepared(MediaPlayer mp) { 
    LayoutInflater inflater=LayoutInflater.from(this); 
    View view= inflater.inflate(R.layout.activity_playing,null,false); 
    TextView mTextActual=(TextView)view.findViewById(R.id.textactual); 
    TextView mTextDuration=(TextView)view.findViewById(R.id.textduration); 
    SeekBar progress=(SeekBar)view.findViewById(R.id.seekbar); 


    String duration=new SimpleDateFormat("mm:ss").format(mp.getDuration()); 
    mTextDuration.setText(duration); 
    mp.start(); 
    whilePlaying(); 


} 

@Override 
public void onCompletion(MediaPlayer mp) { 

} 

@Override 
public boolean onError(MediaPlayer mp, int what, int extra) { 
    return false; 
} 

}

回答

0

你没有启动该服务,因此空指针上下文。

+0

ok on onstart i added –

+0

startService(new Intent(this,Playingservice.class)); –

+0

但它无论如何不起作用 –