我已经创建了一项意向服务,可以在后台为我的应用启动音乐。
它正在工作,但我的log-cat充满了消息:
09-14 16:46:30.117:WARN / AudioFlinger(33):写入被阻止76毫秒,7773延迟写入,线程0xb3f0 并没有其他任何东西被记录。
这是我的IntentService:
import android.app.IntentService;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.widget.Toast;
public class MusicService extends IntentService {
MediaPlayer mPlayer;
private OnErrorListener mErrorListener;
public MusicService() {
super("MusicService");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
// Normally we would do some work here, like download a file.
}
///////////////////////////////////////////////////////////
@Override
public int onStartCommand (Intent intent, int flags, int startId)
{
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
mPlayer.setLooping(true);
mPlayer.start();
return super.onStartCommand(intent,flags,startId);
}
@Override
public void onCreate ()
{
super.onCreate();
// try{
mPlayer = MediaPlayer.create(this, R.raw.jingle);
//}catch (IllegalArgumentException e) {
//e.printStackTrace();
//}catch (IllegalStateException e ) {
//e.printStackTrace();
//}
if(mPlayer!= null)
{
mPlayer.setLooping(true); // Set looping
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
onPlayError();
return true;
}
});
}
private void onPlayError() {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
答案 0 :(得分:-2)
需要权限。将它们放在AndroidManifest.xml中:
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
我在android模拟器2.2下测试了它,所以我的minSdkVersion是8。