安卓音乐播放器,无从下手零点异常服务? [英] Android:Music Player,Unable to start service with null point exception?
本文介绍了安卓音乐播放器,无从下手零点异常服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有错误,直到我添加广播接收器显示seekbar.The应用程序的进展之前,做工精细。
code的活动。
包source.justanothermusicplayer;的Bean;
进口的java.util.ArrayList;
进口source.justanothermusicplayer.classes.SongDetails;
进口source.justanothermusicplayer.service.Music_service;
进口android.app.Activity;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.content.pm.ActivityInfo;
进口android.media.MediaMetadataRetriever;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.SeekBar;
进口android.widget.Toast;
进口android.widget.SeekBar.OnSeekBarChangeListener;公共类NowPlaying扩展活动实现OnSeekBarChangeListener,
序列化{ 意图serviceIntent;
私人布尔boolMusicPlaying = FALSE; 私人按钮buttonPlayStop ;;
搜索栏搜索栏;
ArrayList的< SongDetails> songdetails =新的ArrayList< SongDetails>();
公共静态最后弦乐BROADCAST_SEEKBAR =source.justanothermusicplayer.sendseekbar;
意图意图; //搜索栏
私人搜索栏搜索栏;
私人诠释seekMax;
私有静态诠释songEnded = 0;
布尔mBroadcastIsRegistered; INT位置= 0; 保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.now_playing);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
意向I = getIntent();
位置= i.getIntExtra(数据2,0);
songdetails = getIntent()getParcelableArrayListExtra(数据1);
尝试{意图=新意图(BROADCAST_SEEKBAR);
serviceIntent =新意图(这一点,Music_service.class);
initViews();
setListeners();
}
赶上(例外五)
{}
playAudio(位置);
buttonPlayStop.setBackgroundResource(R.drawable.pause);
boolMusicPlaying = TRUE; } 私人无效setListeners(){
buttonPlayStop.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
buttonPlayStopClick();
}
});
seekbar.setOnSeekBarChangeListener(本); } //不能正常工作,我也有添加暂停和停止不
私人无效buttonPlayStopClick(){
如果(!boolMusicPlaying){
buttonPlayStop.setBackgroundResource(R.drawable.pause);
playAudio(位置);
boolMusicPlaying = TRUE;
}其他{
如果(boolMusicPlaying){
buttonPlayStop.setBackgroundResource(R.drawable.play);
stopMusic_service();
boolMusicPlaying = FALSE;
}
}
} 私人无效playAudio(INT位置2){ 情况2 =位置;
serviceIntent.putParcelableArrayListExtra(sentAudioLink,songdetails);
serviceIntent.putExtra(postion_service位置); 尝试{
startService(serviceIntent);
}赶上(例外五){ e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass()。的getName()++ e.getMessage(),
Toast.LENGTH_LONG).show();
}
registerReceiver(广播接收器,新的IntentFilter(
Music_service.BROADCAST_ACTION));
;
mBroadcastIsRegistered = TRUE; } 私人无效stopMusic_service(){ 如果(mBroadcastIsRegistered){
尝试{
unregisterReceiver(广播接收器);
mBroadcastIsRegistered = FALSE;
}赶上(例外五){
// Log.e(TAG,在活动错误,E);
// TODO自动生成catch块 e.printStackTrace();
Toast.makeText( getApplicationContext(), e.getClass()。的getName()++ e.getMessage(), Toast.LENGTH_LONG).show();
}
} 尝试{
stopService(serviceIntent); }赶上(例外五){
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass()。的getName()++ e.getMessage(),
Toast.LENGTH_LONG).show();
}
boolMusicPlaying = FALSE;
} 私人无效initViews(){
buttonPlayStop =(按钮)findViewById(R.id.bPlayPause);
buttonPlayStop.setBackgroundResource(R.drawable.play);
搜索栏=(搜索栏)findViewById(R.id.songProgressBar);
} @覆盖
公共无效onProgressChanged(搜索栏某人,INT进步,
布尔FROMUSER){
如果(FROMUSER){
INT seekPos = sb.getProgress();
intent.putExtra(seekpos,seekPos);
sendBroadcast(意向);
}
} 私人无效showPD(意向bufferIntent){
字符串bufferValue = bufferIntent.getStringExtra(缓冲);
INT bufferIntValue =的Integer.parseInt(bufferValue); //当广播缓冲值是1,显示缓冲
//进步对话。
//当广播缓冲值是0,驳回进度
//对话。 开关(bufferIntValue){ //监听2的按钮复位到一个播放按钮
案例2:
buttonPlayStop.setBackgroundResource(R.drawable.play);
打破; }
} 私人广播接收器广播接收器=新的广播接收器(){
@覆盖
公共无效的onReceive(上下文的背景下,意图serviceIntent){
的updateUI(serviceIntent);
}
}; 私人无效的updateUI(意向serviceIntent){
串计数器= serviceIntent.getStringExtra(反);
串mediamax = serviceIntent.getStringExtra(mediamax);
串strSongEnded = serviceIntent.getStringExtra(song_ended);
INT seekProgress =的Integer.parseInt(柜);
seekMax =的Integer.parseInt(mediamax);
songEnded =的Integer.parseInt(strSongEnded);
seekBar.setMax(seekMax);
seekBar.setProgress(seekProgress);
如果(songEnded == 1){
buttonPlayStop.setBackgroundResource(R.drawable.play);
}
} 私人广播接收器broadcastBufferReceiver =新的广播接收器(){
@覆盖
公共无效的onReceive(上下文的背景下,意图bufferIntent){
showPD(bufferIntent);
}
}; @覆盖
保护无效的onPause(){
//注销广播接收器
如果(mBroadcastIsRegistered){
unregisterReceiver(broadcastBufferReceiver);
mBroadcastIsRegistered = FALSE;
}
super.onPause();
} // - onResume注册广播接收器。为了改善,恢复保存
//屏幕数据---
@覆盖
保护无效onResume(){
//注册广播接收器
如果(!mBroadcastIsRegistered){
registerReceiver(broadcastBufferReceiver,新的IntentFilter(
Music_service.BROADCAST_BUFFER));
mBroadcastIsRegistered = TRUE;
}
super.onResume();
} @覆盖
公共无效onStartTrackingTouch(搜索栏搜索栏){
// TODO自动生成方法存根 } @覆盖
公共无效onStopTrackingTouch(搜索栏搜索栏){
// TODO自动生成方法存根 }
} 在此输入code
现在code服务:
进口java.io.IOException异常;
进口的java.util.ArrayList;
进口source.justanothermusicplayer.NowPlaying;
进口source.justanothermusicplayer.R;
进口source.justanothermusicplayer.classes.SongDetails;进口android.app.Notification;
进口android.app.NotificationManager;
进口android.app.PendingIntent;
进口android.app.Service;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.media.MediaPlayer;
进口android.media.MediaPlayer.OnBufferingUpdateListener;
进口android.media.MediaPlayer.OnCompletionListener;
进口android.media.MediaPlayer.OnErrorListener;
进口android.media.MediaPlayer.OnInfoListener;
进口android.media.MediaPlayer.On preparedListener;
进口android.media.MediaPlayer.OnSeekCompleteListener;
进口android.net.Uri;
进口android.os.Handler;
进口android.os.IBinder;
进口android.telephony.PhoneStateListener;
进口android.telephony.TelephonyManager;
进口android.util.Log;
进口android.widget.Toast;公共类Music_service扩展服务实现OnCompletionListener,
在preparedListener,OnErrorListener,OnSeekCompleteListener,
OnInfoListener {
私有静态最后弦乐TAG =TELSERVICE; ArrayList的< SongDetails> songdetails =新的ArrayList< SongDetails>();
MediaPlayer的熔点为新的MediaPlayer();
意图bufferIntent;
INT位置;
私有静态最终诠释NOTIFICATION_ID = 1;
私人布尔isPausedInCall = FALSE;
私人PhoneStateListener phoneStateListener;
私人TelephonyManager telephonyManager;
私人INT headsetSwitch = 1;
公共静态最后弦乐BROADCAST_BUFFER =source.justanothermusicplayer.broadcastbuffer; // ---为搜索栏处理变量---
串sntSeekPos;
诠释intSeekPos;
INT mediaPosition;
诠释mediaMax;
//意图意图;
私人最终处理程序处理程序=新的处理程序();
私有静态诠释songEnded;
意图seekIntent; 公共静态最后弦乐BROADCAST_ACTION =source.justanothermusicplayer.seekprogress; @覆盖
公共无效的onCreate(){
mp.setOnCompletionListener(本);
mp.setOn preparedListener(本);
mp.setOnErrorListener(本);
mp.setOnSeekCompleteListener(本);
mp.setOnInfoListener(本);
mp.reset();
bufferIntent =新意图(BROADCAST_BUFFER); //注册耳机接收器
registerReceiver(headsetReceiver,新的IntentFilter(
Intent.ACTION_HEADSET_PLUG));
seekIntent =新意图(BROADCAST_ACTION); } @覆盖
公众诠释onStartCommand(意向意图,诠释旗帜,INT startid){
registerReceiver(广播接收器,新的IntentFilter(
NowPlaying.BROADCAST_SEEKBAR)); Log.v(TAG启动电话); telephonyManager =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
Log.v(TAG启动监听);
phoneStateListener =新PhoneStateListener(){
@覆盖
公共无效onCallStateChanged(INT状态,弦乐incomingNumber){
//字符串stateString =N / A;
Log.v(TAG启动CallStateChange);
开关(州){
案例TelephonyManager.CALL_STATE_OFFHOOK:
案例TelephonyManager.CALL_STATE_RINGING:
如果(熔点!= NULL){
pauseMedia();
isPausedInCall = TRUE;
} 打破;
案例TelephonyManager.CALL_STATE_IDLE:
//电话处于闲置状态。开始播放。
如果(熔点!= NULL){
如果(isPausedInCall){
isPausedInCall = FALSE;
playMedia();
} }
打破;
} } }; //注册与电话经理监听器
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE); initNotification();
songdetails = intent.getParcelableArrayListExtra(sentAudioLink);
位置= intent.getIntExtra(postion_service,0); mp.reset(); //设置使用strAudioLink值MediaPlayer的数据源
//如果(!mp.isPlaying())
{
尝试{
mp.setDataSource(这一点,
Uri.parse(songdetails.get(位置)。路径)); }赶上(抛出:IllegalArgumentException五){
e.printStackTrace();
}赶上(IllegalStateException异常五){
e.printStackTrace();
}赶上(IOException异常五){
}赶上(例外五){
}
尝试{
MP prepare()。
}赶上(例外五){
// TODO自动生成catch块
e.printStackTrace();
} } setupHandler(); 返回START_STICKY;
} 私人无效setupHandler(){
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI,1000); // 1秒
} 私人Runnable接口sendUpdatesToUI =新的Runnable(){
公共无效的run(){
// // Log.d(TAGsendUpdatesToUI进入了); LogMediaPosition(); handler.postDelayed(这一点,1000); //2秒 }
}; 私人无效LogMediaPosition(){
// // Log.d(TAGLogMediaPosition进入了);
如果(mp.isPlaying()){
mediaPosition = mp.getCurrentPosition();
//如果(mediaPosition< 1){
// Toast.makeText(这一点,缓冲......,Toast.LENGTH_SHORT).show();
//}
mediaMax = mp.getDuration();
// seekIntent.putExtra(时代,新的Date()的toLocaleString());
seekIntent.putExtra(反,将String.valueOf(mediaPosition));
seekIntent.putExtra(mediamax,将String.valueOf(mediaMax));
seekIntent.putExtra(song_ended,将String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
} 私人广播接收器广播接收器=新的广播接收器(){
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
updateSeekPos(意向);
}
}; //更新征询活动位置
公共无效updateSeekPos(意向意图){
INT seekPos = intent.getIntExtra(seekpos,0);
如果(mp.isPlaying()){
handler.removeCallbacks(sendUpdatesToUI);
mp.seekTo(seekPos);
setupHandler();
} } 广播接收器headsetReceiver =新的广播接收器(){ 私人布尔headsetConnected = FALSE; @覆盖
公共无效的onReceive(上下文的背景下,意图意图){
// TODO自动生成方法存根
// Log.v(TAGACTION_HEADSET_PLUG意图收到);
如果(intent.hasExtra(国家)){
如果(headsetConnected&安培;&安培; intent.getIntExtra(国家,0)== 0){
headsetConnected = FALSE;
headsetSwitch = 0;
// Log.v(TAG,国家=耳机断开连接);
// headsetDisconnected();
}否则如果(!headsetConnected
&功放;&安培; intent.getIntExtra(国家,0)== 1){
headsetConnected = TRUE;
headsetSwitch = 1;
// Log.v(TAG,国家=耳机连接);
} } 开关(headsetSwitch){
情况下(0):
headsetDisconnected();
打破;
情况1):
打破;
}
} 私人无效headsetDisconnected(){
stopMedia();
stopSelf();
} }; @覆盖
公共无效的onDestroy(){
super.onDestroy();
如果(熔点!= NULL){
如果(mp.isPlaying()){
mp.stop();
}
mp.release();
}
如果(phoneStateListener!= NULL){
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
cancelNotification();
unregisterReceiver(广播接收器); unregisterReceiver(headsetReceiver);
handler.removeCallbacks(sendUpdatesToUI); } 私人无效initNotification(){
字符串NS = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =(NotificationManager)getSystemService(NS);
INT图标= R.drawable.ic_launcher;
CharSequence的tickerText =教程:音乐服务;
时长= System.currentTimeMillis的();
通知通知=新的通知(图标,tickerText时);
notification.flags = Notification.FLAG_ONGOING_EVENT;
上下文的背景下= getApplicationContext();
CharSequence的contentTitle =音乐服务应用教程;
CharSequence的contentText =一边听音乐一边执行其他任务;
意图notificationIntent =新意图(这一点,NowPlaying.class);
的PendingIntent contentIntent = PendingIntent.getActivity(上下文,0,
notificationIntent,0);
notification.setLatestEventInfo(背景下,contentTitle,contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID,通知);
} //取消通知
私人无效cancelNotification(){
字符串NS = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =(NotificationManager)getSystemService(NS);
mNotificationManager.cancel(NOTIFICATION_ID);
} 私人无效resetButtonPlayStopBroadcast(){
// Log.v(TAGBufferCompleteSent);
bufferIntent.putExtra(缓冲,2);
sendBroadcast(bufferIntent);
} @覆盖
公众的IBinder onBind(意向意图){
// TODO自动生成方法存根
返回null;
} @覆盖
公共无效onCompletion(MediaPlayer的MP2){
stopMedia();
位置=位置+ 1; 尝试{
// mp.setDataSource(songdetails.get(位置)。路径);
mp.setDataSource(这一点,Uri.parse(songdetails.get(位置)。路径));
MP prepare()。
}赶上(抛出:IllegalArgumentException五){
e.printStackTrace();
}赶上(SecurityException异常五){
e.printStackTrace();
}赶上(IllegalStateException异常五){
e.printStackTrace();
}赶上(例外五){
e.printStackTrace();
} } 公共无效stopMedia(){
如果(mp.isPlaying()){
mp.stop();
}
mp.reset();
} 公共无效playMedia(){
//如果(!mp.isPlaying())
{
mp.start();
}
} 公共无效pauseMedia(){
// Log.v(TAG,暂停传媒);
如果(mp.isPlaying()){
mp.pause();
} } @覆盖
在prepared(MediaPlayer的为arg0)公共无效{
playMedia(); } @覆盖
公共布尔的onError(MediaPlayer的熔点,诠释了什么,整型附加){
// TODO自动生成方法存根
返回false;
} @覆盖
公共无效onSeekComplete(MediaPlayer的MP2){
如果(!mp.isPlaying()){
playMedia();
Toast.makeText(这一点,
SeekComplete,Toast.LENGTH_SHORT).show();
} } @覆盖
公共布尔onInfo(MediaPlayer的为arg0,ARG1 INT,INT ARG2){
// TODO自动生成方法存根
返回false;
}}
现在错误日志
10-09 21:34:27.751:E / AndroidRuntime(553):致命异常:主要
10-09 21:34:27.751:E / AndroidRuntime(553):了java.lang.RuntimeException:错误接收source.justanothermusicplayer.NowPlaying $ 1条广播意向{行动= source.justanothermusicplayer.seekprogress FLG = 0×10(有临时演员)} @ 40fa2e50
10-09 21:34:27.751:E / AndroidRuntime(553):在android.app.LoadedApk $ ReceiverDispatcher $ Args.run(LoadedApk.java:737)
10-09 21:34:27.751:E / AndroidRuntime(553):在android.os.Handler.handleCallback(Handler.java:605)
10-09 21:34:27.751:E / AndroidRuntime(553):在android.os.Handler.dispatchMessage(Handler.java:92)
10-09 21:34:27.751:E / AndroidRuntime(553):在android.os.Looper.loop(Looper.java:137)
10-09 21:34:27.751:E / AndroidRuntime(553):在android.app.ActivityThread.main(ActivityThread.java:4340)
10-09 21:34:27.751:E / AndroidRuntime(553):在java.lang.reflect.Method.invokeNative(本机方法)
10-09 21:34:27.751:E / AndroidRuntime(553):在java.lang.reflect.Method.invoke(Method.java:511)
10-09 21:34:27.751:E / AndroidRuntime(553):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
10-09 21:34:27.751:E / AndroidRuntime(553):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-09 21:34:27.751:E / AndroidRuntime(553):在dalvik.system.NativeStart.main(本机方法)
10-09 21:34:27.751:E / AndroidRuntime(553):致:显示java.lang.NullPointerException
10-09 21:34:27.751:E / AndroidRuntime(553):在source.justanothermusicplayer.NowPlaying.updateUI(NowPlaying.java:196)
10-09 21:34:27.751:E / AndroidRuntime(553):在source.justanothermusicplayer.NowPlaying.access $ 0(NowPlaying.java:189)
10-09 21:34:27.751:E / AndroidRuntime(553):在source.justanothermusicplayer.NowPlaying $ 1.onReceive(NowPlaying.java:185)
10-09 21:34:27.751:E / AndroidRuntime(553):在android.app.LoadedApk $ ReceiverDispatcher $ Args.run(LoadedApk.java:728)
10-09 21:34:27.751:E / AndroidRuntime(553):... 9点多
解决方案
试试这个..
u必须指定的全局seekMax 2次
onStartCommand
的return语句总是
返回START_NOT_STICKY;
只有
个人,对于一个音乐播放器,我认为 START_NOT_STICKY
是正确的答案。如果您的服务已停止出于某种原因,用户应负责再次启动起来。
There were no errors until i added broadcast receiver for showing the progress of the seekbar.The app was working fine before.
Code for the activity.
package source.justanothermusicplayer;
import java.io.Serializable;
import java.util.ArrayList;
import source.justanothermusicplayer.classes.SongDetails;
import source.justanothermusicplayer.service.Music_service;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class NowPlaying extends Activity implements OnSeekBarChangeListener,
Serializable {
Intent serviceIntent;
private boolean boolMusicPlaying = false;
private Button buttonPlayStop;;
SeekBar seekbar;
ArrayList<SongDetails> songdetails = new ArrayList<SongDetails>();
public static final String BROADCAST_SEEKBAR = "source.justanothermusicplayer.sendseekbar";
Intent intent;
// Seekbar
private SeekBar seekBar;
private int seekMax;
private static int songEnded = 0;
boolean mBroadcastIsRegistered;
int position = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.now_playing);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent i = getIntent();
position = i.getIntExtra("Data2", 0);
songdetails = getIntent().getParcelableArrayListExtra("Data1");
try {intent = new Intent(BROADCAST_SEEKBAR);
serviceIntent = new Intent(this, Music_service.class);
initViews();
setListeners();
}
catch(Exception e)
{}
playAudio(position);
buttonPlayStop.setBackgroundResource(R.drawable.pause);
boolMusicPlaying = true;
}
private void setListeners() {
buttonPlayStop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
buttonPlayStopClick();
}
});
seekbar.setOnSeekBarChangeListener(this);
}
// not working correctly,also i have to add pause and not stop
private void buttonPlayStopClick() {
if (!boolMusicPlaying) {
buttonPlayStop.setBackgroundResource(R.drawable.pause);
playAudio(position);
boolMusicPlaying = true;
} else {
if (boolMusicPlaying) {
buttonPlayStop.setBackgroundResource(R.drawable.play);
stopMusic_service();
boolMusicPlaying = false;
}
}
}
private void playAudio(int position2) {
position2 = position;
serviceIntent.putParcelableArrayListExtra("sentAudioLink", songdetails);
serviceIntent.putExtra("postion_service", position);
try {
startService(serviceIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
registerReceiver(broadcastReceiver, new IntentFilter(
Music_service.BROADCAST_ACTION));
;
mBroadcastIsRegistered = true;
}
private void stopMusic_service() {
if (mBroadcastIsRegistered) {
try {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
} catch (Exception e) {
// Log.e(TAG, "Error in Activity", e);
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
try {
stopService(serviceIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
boolMusicPlaying = false;
}
private void initViews() {
buttonPlayStop = (Button) findViewById(R.id.bPlayPause);
buttonPlayStop.setBackgroundResource(R.drawable.play);
seekbar = (SeekBar) findViewById(R.id.songProgressBar);
}
@Override
public void onProgressChanged(SeekBar sb, int progress,
boolean fromUser) {
if (fromUser) {
int seekPos = sb.getProgress();
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
}
}
private void showPD(Intent bufferIntent) {
String bufferValue = bufferIntent.getStringExtra("buffering");
int bufferIntValue = Integer.parseInt(bufferValue);
// When the broadcasted "buffering" value is 1, show "Buffering"
// progress dialogue.
// When the broadcasted "buffering" value is 0, dismiss the progress
// dialogue.
switch (bufferIntValue) {
// Listen for "2" to reset the button to a play button
case 2:
buttonPlayStop.setBackgroundResource(R.drawable.play);
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent serviceIntent) {
updateUI(serviceIntent);
}
};
private void updateUI(Intent serviceIntent) {
String counter = serviceIntent.getStringExtra("counter");
String mediamax = serviceIntent.getStringExtra("mediamax");
String strSongEnded = serviceIntent.getStringExtra("song_ended");
int seekProgress = Integer.parseInt(counter);
seekMax = Integer.parseInt(mediamax);
songEnded = Integer.parseInt(strSongEnded);
seekBar.setMax(seekMax);
seekBar.setProgress(seekProgress);
if (songEnded == 1) {
buttonPlayStop.setBackgroundResource(R.drawable.play);
}
}
private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent bufferIntent) {
showPD(bufferIntent);
}
};
@Override
protected void onPause() {
// Unregister broadcast receiver
if (mBroadcastIsRegistered) {
unregisterReceiver(broadcastBufferReceiver);
mBroadcastIsRegistered = false;
}
super.onPause();
}
// -- onResume register broadcast receiver. To improve, retrieve saved
// screen data ---
@Override
protected void onResume() {
// Register broadcast receiver
if (!mBroadcastIsRegistered) {
registerReceiver(broadcastBufferReceiver, new IntentFilter(
Music_service.BROADCAST_BUFFER));
mBroadcastIsRegistered = true;
}
super.onResume();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
enter code here
now code for service:
import java.io.IOException;
import java.util.ArrayList;
import source.justanothermusicplayer.NowPlaying;
import source.justanothermusicplayer.R;
import source.justanothermusicplayer.classes.SongDetails;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class Music_service extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnSeekCompleteListener,
OnInfoListener {
private static final String TAG = "TELSERVICE";
ArrayList<SongDetails> songdetails = new ArrayList<SongDetails>();
MediaPlayer mp = new MediaPlayer();
Intent bufferIntent;
int position;
private static final int NOTIFICATION_ID = 1;
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private int headsetSwitch = 1;
public static final String BROADCAST_BUFFER = "source.justanothermusicplayer.broadcastbuffer";
// ---Variables for seekbar processing---
String sntSeekPos;
int intSeekPos;
int mediaPosition;
int mediaMax;
// Intent intent;
private final Handler handler = new Handler();
private static int songEnded;
Intent seekIntent;
public static final String BROADCAST_ACTION = "source.justanothermusicplayer.seekprogress";
@Override
public void onCreate() {
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setOnSeekCompleteListener(this);
mp.setOnInfoListener(this);
mp.reset();
bufferIntent = new Intent(BROADCAST_BUFFER);
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
seekIntent = new Intent(BROADCAST_ACTION);
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
registerReceiver(broadcastReceiver, new IntentFilter(
NowPlaying.BROADCAST_SEEKBAR));
Log.v(TAG, "Starting telephony");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Log.v(TAG, "Starting listener");
phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
// String stateString = "N/A";
Log.v(TAG, "Starting CallStateChange");
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mp != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mp != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
initNotification();
songdetails = intent.getParcelableArrayListExtra("sentAudioLink");
position = intent.getIntExtra("postion_service", 0);
mp.reset();
// Set up the MediaPlayer data source using the strAudioLink value
// if (!mp.isPlaying())
{
try {
mp.setDataSource(this,
Uri.parse(songdetails.get(position).Path));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
} catch (Exception e) {
}
try {
mp.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setupHandler();
return START_STICKY;
}
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
// // Log.d(TAG, "entered sendUpdatesToUI");
LogMediaPosition();
handler.postDelayed(this, 1000); // 2 seconds
}
};
private void LogMediaPosition() {
// // Log.d(TAG, "entered LogMediaPosition");
if (mp.isPlaying()) {
mediaPosition = mp.getCurrentPosition();
// if (mediaPosition < 1) {
// Toast.makeText(this, "Buffering...", Toast.LENGTH_SHORT).show();
// }
mediaMax = mp.getDuration();
// seekIntent.putExtra("time", new Date().toLocaleString());
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mp.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mp.seekTo(seekPos);
setupHandler();
}
}
BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Log.v(TAG, "ACTION_HEADSET_PLUG Intent received");
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
// Log.v(TAG, "State = Headset disconnected");
// headsetDisconnected();
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
// Log.v(TAG, "State = Headset connected");
}
}
switch (headsetSwitch) {
case (0):
headsetDisconnected();
break;
case (1):
break;
}
}
private void headsetDisconnected() {
stopMedia();
stopSelf();
}
};
@Override
public void onDestroy() {
super.onDestroy();
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
cancelNotification();
unregisterReceiver(broadcastReceiver);
unregisterReceiver(headsetReceiver);
handler.removeCallbacks(sendUpdatesToUI);
}
private void initNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Tutorial: Music In Service";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
CharSequence contentTitle = "Music In Service App Tutorial";
CharSequence contentText = "Listen To Music While Performing Other Tasks";
Intent notificationIntent = new Intent(this, NowPlaying.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
// Cancel Notification
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
private void resetButtonPlayStopBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "2");
sendBroadcast(bufferIntent);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCompletion(MediaPlayer mp2) {
stopMedia();
position = position + 1;
try {
// mp.setDataSource(songdetails.get(position).Path);
mp.setDataSource(this, Uri.parse(songdetails.get(position).Path));
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopMedia() {
if (mp.isPlaying()) {
mp.stop();
}
mp.reset();
}
public void playMedia() {
// if (!mp.isPlaying())
{
mp.start();
}
}
public void pauseMedia() {
// Log.v(TAG, "Pause Media");
if (mp.isPlaying()) {
mp.pause();
}
}
@Override
public void onPrepared(MediaPlayer arg0) {
playMedia();
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onSeekComplete(MediaPlayer mp2) {
if (!mp.isPlaying()){
playMedia();
Toast.makeText(this,
"SeekComplete", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
}
now error log
10-09 21:34:27.751: E/AndroidRuntime(553): FATAL EXCEPTION: main
10-09 21:34:27.751: E/AndroidRuntime(553): java.lang.RuntimeException: Error receiving broadcast Intent { act=source.justanothermusicplayer.seekprogress flg=0x10 (has extras) } in source.justanothermusicplayer.NowPlaying$1@40fa2e50
10-09 21:34:27.751: E/AndroidRuntime(553): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:737)
10-09 21:34:27.751: E/AndroidRuntime(553): at android.os.Handler.handleCallback(Handler.java:605)
10-09 21:34:27.751: E/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:92)
10-09 21:34:27.751: E/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:137)
10-09 21:34:27.751: E/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4340)
10-09 21:34:27.751: E/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 21:34:27.751: E/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:511)
10-09 21:34:27.751: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-09 21:34:27.751: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-09 21:34:27.751: E/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method)
10-09 21:34:27.751: E/AndroidRuntime(553): Caused by: java.lang.NullPointerException
10-09 21:34:27.751: E/AndroidRuntime(553): at source.justanothermusicplayer.NowPlaying.updateUI(NowPlaying.java:196)
10-09 21:34:27.751: E/AndroidRuntime(553): at source.justanothermusicplayer.NowPlaying.access$0(NowPlaying.java:189)
10-09 21:34:27.751: E/AndroidRuntime(553): at source.justanothermusicplayer.NowPlaying$1.onReceive(NowPlaying.java:185)
10-09 21:34:27.751: E/AndroidRuntime(553): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
10-09 21:34:27.751: E/AndroidRuntime(553): ... 9 more
解决方案
try this..
u have specified global seekMax 2 times
return statement of onStartCommand
always
return START_NOT_STICKY;
only
Personally, for a music player, I argue that START_NOT_STICKY
is the right answer. If your service is stopped for whatever reason, the user should be in charge of starting it up again.
这篇关于安卓音乐播放器,无从下手零点异常服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文