无法在 onCreate 中获取歌曲持续时间,但可以在按下按钮时获取它
我有一个自定义媒体服务和一个与其通信但不绑定到该服务的音频播放器类。
当我创建 MyService 的对象并编写代码时:- onCreate
中的 myService.player.getDuration()
我在这一行收到空指针异常。
但是,如果我在同一屏幕上单击某个按钮侦听器时编写此代码,那么我会得到确切的持续时间。
我已尝试了所有可能的语法来解决此问题,但仍然无法解决问题。
** 我的服务代码是:-**
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);
}
};
};
I have a custom media service and an audio player class which communicates with it but is not bound to the service.
When I create an object of MyService and write the code :-myService.player.getDuration()
in onCreate
I get the null pointer exception on this line.
But if I write this code on click of some button listener on the same screen then I get the exact duration.
I have tried every possible syntax to solve this but m still not able to resolve the problem.
** The code of my service is :-**
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();
}
The code of Audio Player is :-
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);
}
};
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是一个语法问题;而是一个问题。这是一个变量初始化问题。当该行在
onCreate()
中执行时,myService
或myService.player
为null
。检查您的代码以了解初始化它们的位置,并确保在设置它们之前不引用它们。It's not a syntax problem; it's a variable initialization problem. Either
myService
ormyService.player
isnull
when that line executes inonCreate()
. Check your code for where you are initializing these and make sure that you don't reference them before they are set.