gpt4 book ai didi

Android- ListView 、服务媒体播放器和 boolean 标志

转载 作者:行者123 更新时间:2023-11-30 04:36:37 25 4
gpt4 key购买 nike

我目前有一个 listview,当您单击一个项目时,它会运行一个带有 mediaplayer服务。如果我单击 listview 中的另一个项目,正在运行的 service 应该停止并运行新的 service。我正在使用一个 boolean isRunning 设置为 false,当服务创建时它返回 true。然后在 listview 中,我在 if 语句中调用该标志。但是,它并不完全有效。我想我可能做错了。有什么想法吗?

我的描述方式听起来可能令人困惑,所以这是我的 listviewservice 的代码。我只是在案例 3 上测试这个(所以我按下这个项目来启动服务,然后点击案例 2 看它是否会停止它)。

ListView 类:

public class PlaylistActivity extends ListActivity{

private static final String TAG = PlaylistActivity.class.getSimpleName();

// Data to put in the ListAdapter
private String[] sdrPlaylistNames = new String[] {
"Best of June 2011", "Best of May 2011", "Dubstep",
"House", "Other"};

private ListAdapter sdrListAdapter;
Intent playbackServiceIntentBOJ, playbackServiceIntentBOM, playbackServiceIntentDUB;



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlists_layout);
//fill the screen with the list adapter
playlistFillData();

playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
Log.d(TAG, "Made DUB Service Intent");
}

public void playlistFillData() {
//create and set up the Array adapter for the list view
ArrayAdapter sdrListAdapter = new ArrayAdapter(this, R.layout.list_item, sdrPlaylistNames);
setListAdapter(sdrListAdapter);
}

//set up the on list item Click
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//create a switch so that each list item is a different playlist
switch(position){
case 0:
Intent BOJintent = new Intent(this, BOJAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOJintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();

// Again, replace the view
PlaylistGroup.group.replaceView(view);

// playbackServiceIntentBOJ = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOJ Intent");
// startService(playbackServiceIntentBOJ);
Log.d(TAG, "started BOJ Service");

break;
case 1:
Intent BOMintent = new Intent(this, BOMAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view2 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOMintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();

// Again, replace the view
PlaylistGroup.group.replaceView(view2);
Log.d(TAG, "Replace view");

//getApplicationContext().stopService(playbackServiceIntentBOJ);

//playbackServiceIntentBOM = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOM Service Intent");
// startService(playbackServiceIntentBOM);
Log.d(TAG, "started BOM Service");

if(DUBAudioActivity.isRunningDUB = true){
stopService(playbackServiceIntentDUB);
Log.d(TAG, "stop service isRunningDUB");
}
//
break;
case 2:

Intent DUBIntent = new Intent (this, DUBAudioActivity.class);
View view3 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", DUBIntent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
PlaylistGroup.group.replaceView(view3);
Log.d(TAG, "Replace view");

startService(playbackServiceIntentDUB);
Log.d(TAG, "started DUB service");

break;

}


}


}

服务等级:

public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{

Toast loadingMessage;

private static final String TAG = DUBAudioService.class.getSimpleName();

public static boolean isRunningDUB = false;

//to keep track of the playlist item
Vector<PlaylistFile> playlistItems;

MediaPlayer mediaPlayer;

String baseURL = "";

//keep track of which item from the vector we are on
int currentPlaylistltemNumber = 0;

public class DUBBackgroundAudioServiceBinder extends Binder {
DUBAudioService getService() {
return DUBAudioService.this;
}
}

private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();



@Override
public IBinder onBind(Intent intent) {
return basBinderDUB;
}

@Override
public void onCreate() {
Log.v("PLAYERSERVICE", "onCreate");
mediaPlayer = new MediaPlayer();
new MusicAsync().execute();
Log.d(TAG, "execute'd async");
mediaPlayer.setOnPreparedListener(this);
Log.d(TAG, "set on prepared listener");
mediaPlayer.setOnCompletionListener(this);
Log.d(TAG, "set on completion listener");

isRunningDUB = true;
Log.d(TAG, "isRunningRUB = true");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if (!mediaPlayer.isPlaying()) {
// mediaPlayer.start();
//}
return START_STICKY;
}


class MusicAsync extends AsyncTask<Void,Void,Void>{
@Override
protected void onPreExecute(){
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub

//create empty vector
playlistItems = new Vector<PlaylistFile>();

//HTTP client library
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here

Log.v("URI",getRequest.getURI().toString());

try {
HttpResponse httpResponse = httpClient.execute(getRequest);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
}
else {
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = bufferedReader.readLine()) != null) {
Log.v("PLAYLISTLINE","ORIG: " + line);

if (line.startsWith("#")) {
//Metadata
//Could do more with this but not fo now
} else if (line.length() > 0) {
String filePath = "";
if (line.startsWith("http://")) {
// Assume its a full URL
filePath = line;
} else {
//Assume it’s relative
filePath = getRequest.getURI().resolve(line).toString();
}

PlaylistFile playlistFile = new PlaylistFile(filePath);
playlistItems.add (playlistFile);
}
}
inputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e. printStackTrace();
}


currentPlaylistltemNumber = 0;
if (playlistItems.size() > 0)
{
String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);

mediaPlayer.prepareAsync();}
catch (IllegalArgumentException e)
{ e.printStackTrace();
}catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();}
}



return null;
}
//
protected void onPostExecute(Void result){
//playButton. setEnabled (false);
}
}



@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);


}

public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "music stopp'd");
}
//mediaPlayer.release();
Log.d(TAG, "onDestroy");
}

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub\
Log.d(TAG, "music is prepared and will start");
mediaPlayer.start();
}

public void onCompletion(MediaPlayer _mediaPlayer) {
Log.d(TAG, "Song completed, next song");
mediaPlayer.stop();
mediaPlayer.reset();
if (playlistItems.size() > currentPlaylistltemNumber + 1) {
currentPlaylistltemNumber++;
String path =
((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e. printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

class PlaylistFile {
String filePath;
public PlaylistFile(String _filePath) {
filePath = _filePath;
}
public void setFilePath(String _filePath) {
filePath = _filePath;
}
public String getFilePath() {
return filePath;
}
}


public void playSong(){
Log.d(TAG, "start'd");
mediaPlayer.start();
}

public void pauseSong(){
Log.d(TAG, "pause'd");
mediaPlayer.pause();
}



}

最佳答案

这变得相当复杂,但我使用以下方法查看我的服务是否正在运行:

private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}

我将其添加到我的 listview 类中,并在每种情况下放置 if 语句以查看它是否正在运行,如果是则停止 service

我还公开了所有绑定(bind)连接,以便 ListView 类可以访问它们并在单击时启动它们。

如果有人想进一步了解等,请给我留言。

关于Android- ListView 、服务媒体播放器和 boolean 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6725937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com