我在下面有我的 Activity ,它使用一些帮助类播放 ShoutCastURL 流
代码:
import java.net.MalformedURLException;
import com.androidworkz.androidshoutcastlib.AndroidShoutcastLib;
import com.androidworkz.androidshoutcastlib.InvalidStreamURLException;
import com.androidworkz.androidshoutcastlib.Metadata;
import com.androidworkz.androidshoutcastlib.MetadataListener;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Player extends Activity implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnBufferingUpdateListener, MusicFocusable {
private Boolean playState = false;
private String station = "http://38.101.195.5:9156";
public static final float DUCK_VOLUME = 0.1f;
private String artistName = null;
private String trackName = null;
private TextView artist;
private TextView track;
private TextView status;
private Button play;
enum AudioFocus {
NoFocusNoDuck, // we don't have audio focus, and can't duck
NoFocusCanDuck, // we don't have focus, but can play at a low volume
// ("ducking")
Focused // we have full audio focus
}
private AudioFocus mAudioFocus = AudioFocus.NoFocusNoDuck;
private MediaPlayer mPlayer = null;
private AndroidShoutcastLib shoutcast;
private AudioManager mAudioManager;
AudioFocusHelper mAudioFocusHelper = null;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
// create the Audio Focus Helper, if the Audio Focus feature is
// available (SDK 8 or above)
if (android.os.Build.VERSION.SDK_INT >= 8) {
mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(),
this);
}
else {
mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus
}
status = (TextView) findViewById(R.id.status);
artist = (TextView) findViewById(R.id.artist);
artist.setSelected(true);
track = (TextView) findViewById(R.id.track);
track.setSelected(true);
play = (Button) findViewById(R.id.play);
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View btn) {
if (!playState) {
play.setText("Pause");
handler.postDelayed(handlePlayRequest, 300);
}
else {
play.setText("Play");
status.setText("Press Play");
handler.postDelayed(handlePlayRequest, 300);
}
}
});
shoutcast = new AndroidShoutcastLib();
try {
shoutcast.setShoutcastUrl(station);
} catch (InvalidStreamURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shoutcast.setOnMetadataChangedListener(new MetadataListener(){
@Override
public void OnMetadataChanged(Metadata item) {
artistName = item.artist;
trackName = item.track;
updateMeta();
}
});
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public void onDestroy() {
super.onDestroy();
shoutcast = null;
handler.removeCallbacks(handlePlayRequest);
}
public void updateMeta() {
handler.post(new Runnable() {
@Override
public void run() {
// This gets executed on the UI thread so it can safely modify Views
artist.setText(artistName);
track.setText(trackName);
}
});
}
private final Runnable handlePlayRequest = new Runnable() {
public void run() {
if (playState) {
Log.d("Player", "Stop Called");
giveUpAudioFocus();
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
shoutcast.stopStream();
mPlayer = null;
playState = false;
}
else {
Log.d("Player", "Play Called");
createMediaPlayer();
getAudioFocus();
try {
mPlayer.setDataSource(shoutcast.startStream());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidStreamURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.prepareAsync();
}
}
};
private void createMediaPlayer() {
mPlayer = new MediaPlayer();
// Make sure the media player will acquire a wake-lock while
// playing. If we don't do
// that, the CPU might go to sleep while the song is playing,
// causing playback to stop.
//
// Remember that to use this, we have to declare the
// android.permission.WAKE_LOCK
// permission in AndroidManifest.xml.
mPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
// we want the media player to notify us when it's ready preparing,
// and when it's done
// playing:
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
}
private void startPlayer() {
mPlayer.setVolume(1.0f, 1.0f);
if (!mPlayer.isPlaying()) {
Log.d("Player", "Starting Playback");
mPlayer.start();
playState = true;
status.setText("Streaming");
}
}
private void getAudioFocus() {
if (mAudioFocus != AudioFocus.Focused && mAudioFocusHelper != null
&& mAudioFocusHelper.requestFocus())
mAudioFocus = AudioFocus.Focused;
}
private void giveUpAudioFocus() {
if (mAudioFocus == AudioFocus.Focused && mAudioFocusHelper != null
&& mAudioFocusHelper.abandonFocus())
mAudioFocus = AudioFocus.NoFocusNoDuck;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_player, menu);
return true;
}
@Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
playState = false;
handler.post(handlePlayRequest);
return false;
}
@Override
public void onPrepared(MediaPlayer arg0) {
startPlayer();
}
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
@Override
public void onGainedAudioFocus() {
// TODO Auto-generated method stub
}
@Override
public void onLostAudioFocus(boolean canDuck) {
// TODO Auto-generated method stub
}
}
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Player extends Activity implements OnClickListener {
private Boolean playState = false;
public static final float DUCK_VOLUME = 0.1f;
private String artistName = null;
private String trackName = null;
private TextView artist;
private TextView track;
private TextView status;
private Button play;
Intent playbackServiceIntent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
// create the Audio Focus Helper, if the Audio Focus feature is
// available (SDK 8 or above)
status = (TextView) findViewById(R.id.status);
artist = (TextView) findViewById(R.id.artist);
artist.setSelected(true);
track = (TextView) findViewById(R.id.track);
track.setSelected(true);
play = (Button) findViewById(R.id.play);
play.setOnClickListener(this);
playbackServiceIntent = new Intent(this, BackGroundService.class);
}
@Override
public void onClick(View v) {
if (v == play) {
startService(playbackServiceIntent);
Log.d("hi>>>>>", "gjgj");
finish();
}
}
}
import com.androidworkz.androidshoutcastlib.AndroidShoutcastLib;
import com.androidworkz.androidshoutcastlib.InvalidStreamURLException;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
public class BackGroundService extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnBufferingUpdateListener,
MusicFocusable {
private Boolean playState = false;
private String station = "http://38.101.195.5:9156";
public static final float DUCK_VOLUME = 0.1f;
Runnable handlePlayRequest;
enum AudioFocus {
NoFocusNoDuck, // we don't have audio focus, and can't duck
NoFocusCanDuck, // we don't have focus, but can play at a low volume
// ("ducking")
Focused // we have full audio focus
}
private AudioFocus mAudioFocus = AudioFocus.NoFocusNoDuck;
private MediaPlayer mPlayer = null;
private AndroidShoutcastLib shoutcast;
private AudioManager mAudioManager;
AudioFocusHelper mAudioFocusHelper = null;
Handler handler = new Handler();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand>>>", "onStartCommand");
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
// create the Audio Focus Helper, if the Audio Focus feature is
// available (SDK 8 or above)
if (android.os.Build.VERSION.SDK_INT >= 8) {
mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(),
this);
} else {
mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
// "have" audio focus
}
shoutcast = new AndroidShoutcastLib();
try {
Log.d("Station>>>", station);
shoutcast.setShoutcastUrl(station);
} catch (InvalidStreamURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new BackgroundSound().execute();
return START_STICKY;
}
public void onDestroy() {
Log.d("onDestroy>>>", "onDestroy");
if (mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.release();
}
@Override
public void onGainedAudioFocus() {
// TODO Auto-generated method stub
}
@Override
public void onLostAudioFocus(boolean canDuck) {
// TODO Auto-generated method stub
}
@Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
mPlayer.start();
}
private void giveUpAudioFocus() {
if (mAudioFocus == AudioFocus.Focused && mAudioFocusHelper != null
&& mAudioFocusHelper.abandonFocus())
mAudioFocus = AudioFocus.NoFocusNoDuck;
}
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
stopSelf();
}
private void getAudioFocus() {
if (mAudioFocus != AudioFocus.Focused && mAudioFocusHelper != null
&& mAudioFocusHelper.requestFocus())
mAudioFocus = AudioFocus.Focused;
}
private void createMediaPlayer() {
mPlayer = new MediaPlayer();
// Make sure the media player will acquire a wake-lock while
// playing. If we don't do
// that, the CPU might go to sleep while the song is playing,
// causing playback to stop.
//
// Remember that to use this, we have to declare the
// android.permission.WAKE_LOCK
// permission in AndroidManifest.xml.
mPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
// we want the media player to notify us when it's ready preparing,
// and when it's done
// playing:
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
}
private class BackgroundSound extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.d("doInBackground>>>", "doInBackground");
Log.d("run>>>", "run");
if (playState) {
Log.d("Player", "Stop Called");
giveUpAudioFocus();
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
shoutcast.stopStream();
mPlayer = null;
playState = false;
} else {
Log.d("Player", "Play Called");
createMediaPlayer();
getAudioFocus();
try {
mPlayer.setDataSource(shoutcast.startStream());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidStreamURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.prepareAsync();
}
return null;
}
}
}
最佳答案
如果您只想为您的应用播放背景音乐,请在从您的应用启动的线程中播放它/使用 AsyncTask 类为您播放。
服务的概念是在后台运行;根据背景,含义通常是您的应用程序 UI 是 不可见 .确实,它可以像您一样使用(如果您记得停止它),但它是不对的,并且它消耗了您不应该使用的资源。
如果要在 Activity 的后台执行任务,请使用 AsyncTask。
顺便说一下, onStart 已被弃用。当您确实使用服务时,请实现 onStartCommand。
更新:
我认为这段代码对你有用。添加这个类(包含在您的 Activity 类中)。
public class BackgroundSound extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr); player.setLooping(true); // Set looping player.setVolume(100,100); player.start(); return null; } }
BackgroundSound mBackgroundSound = new BackgroundSound();
public void onResume() { super.onResume(); mBackgroundSound.execute(null); }
public void onPause() { super.onPause(); mBackgroundSound.cancel(true); }
关于Android Activity 到 Service 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16355920/
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visitthehelpcenter.关闭9年前。我需要从基于ruby的应用程序使用AmazonSimpleNotificationService,但不知道从哪里开始。您对从哪里开始有什么建议吗?
我正在按照我一直在研究的研讨会实现“服务对象”,我正在构建一个redditAPI应用程序。我需要对象返回一些东西,所以我不能只执行初始化程序中的所有内容。我有这两个选择:选项1:类需要实例化classSubListFromUserdefuser_subscribed_subs(client)@client=client@subreddits=sort_subs_by_name(user_subs_from_reddit)endprivatedefsort_subs_by_name(subreddits)subreddits.sort_by{|sr|sr[:name].downcase}
我有一个关于配置elasticsearch以连接AWSelasticsearch服务以在生产环境中运行项目的问题。我的gem文件:gem'searchkick'gem'faraday_middleware-aws-signers-v4'gem'aws-sdk','~>2'gem"elasticsearch",">=1.0.15"引用:https://github.com/ankane/searchkick我的config/initializers/elasticsearch.rb文件:require"faraday_middleware/aws_signers_v4"ENV["ELAS
文章目录一.搭建集群时出现错误错误日志elasticsearch.logorg.elasticsearch.cluster.block.clusterblockexception:blockedby:[service_unavailable/1/statenotrecovered/initialized];原因:解决方案:一.搭建集群时出现错误错误日志elasticsearch.logorg.elasticsearch.cluster.block.clusterblockexception:blockedby:[service_unavailable/1/statenotrecovered/i
我想知道如何正确注册服务人员,在开发中一切正常,我调用服务人员:if(navigator.serviceWorker){navigator.serviceWorker.register('./sw.js').then(function(reg){if(reg.waiting){reg.waiting.postMessage({action:'skipWaiting'});return;}reg.addEventListener('updatefound',function(){trackInstalling(reg.installing);});varrefreshing;naviga
我正在尝试对使用$http的服务进行单元测试。我正在使用Jasmine,但我一直收到此错误:TypeError:parsedisundefinedinangular.js(line13737)这是我的服务的样子:angular.module('myapp.services',[]).factory('inviteService',['$rootScope','$http',function($rootScope,$http){varinviteService={token:'',getInvite:function(callback,errorCallback){$http.get('
我有一个应用程序模块和单组件应用程序(用于演示我的问题),并出现以下错误:Errorin./AppComponentclassAppComponent_Host-inlinetemplate:0:0causedby:NoproviderforUserService!;Zone:;Task:Promise.then;Value:AppModule代码:import{NgModule}from'@angular/core';import{BrowserModule}from'@angular/platform-browser';import{UserService}from'./compo
我想做这样的事情:angular.module('app',[]).config(['$httpProvider','customAuthService',($httpProvider,customAuthService)->$httpProvider.defaults.transformRequest.push(data)->ifcustomAuthService.isLoggedIndata['api_key']={token:@token}])根据Angularjsdoc,我不能在我的module的configblock中执行此操作,因为那里不允许自定义服务,我也不能在run中执
我有一个定义如下的服务:appServices.service('SharedData',function(){vardata={};functionsetContacts(contacts){data.contacts=contacts;};functiongetContacts(){returndata.contacts;};return{setContacts:setContacts,getContacts:getContacts};});在另一个Controller中,我按如下方式访问数据:$scope.contacts=SharedData.getContacts();一切都
当我打开WAVE(Web可访问性评估工具)扩展程序时,我的服务人员在Chrome中抛出此错误:Uncaught(inpromise)TypeError:Requestscheme'chrome-extension'isunsupportedatsw.js:52(anonymous)@sw.js:52Promise.then(async)(anonymous)@sw.js:50Promise.then(async)(anonymous)@sw.js:45Promise.then(async)(anonymous)@sw.js:38我的服务worker代码是:(function(){'us