Android-列表视图,服务媒体播放器,以及布尔标志 [英] Android- listview, service mediaplayer, and boolean flags

查看:138
本文介绍了Android-列表视图,服务媒体播放器,以及布尔标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个列表视图键,当你点击一个项目运行一个服务媒体播放器。如果我在列表视图点击另一个项目服务的的运行应该停止并运行新的服务。我使用的是布尔 isRunning 设置为false,创建服务时,它返回true。然后在列表视图我认为这种标志在如果语句。然而,它的不完全工作。我想我可以这样做不对。任何想法?

这可能听起来很混乱,我描述它,这里顺便提一下的是code到我的列表视图和我的服务。我只是在情况下3测试这个(所以preSS此项目,将启动该服务,然后单击案例2,看它是否会停止)。

列表视图类:

 公共类PlaylistActivity扩展ListActivity {

    私有静态最后字符串变量= PlaylistActivity.class.getSimpleName();

    //数据将在ListAdapter
    私有String [] sdrPlaylistNames =新的String [] {
            最好的2011年6月,最佳2011年5月,的Dubstep
            豪斯医生,其他};

    私人ListAdapter sdrListAdapter;
    意图playbackServiceIntentBOJ,playbackServiceIntentBOM,playbackServiceIntentDUB;



    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.playlists_layout);
        //填满屏幕上的列表适配器
        playlistFillData();

        playbackServiceIntentDUB =新的意图(这一点,DUBAudioService.class);
        Log.d(TAG,MADE DUB服务意向书);
    }

    公共无效playlistFillData(){
        //创建并设置阵列适配器列表视图
        ArrayAdapter sdrListAdapter =新的ArrayAdapter(这一点,R.layout.list_item,sdrPlaylistNames);
        setListAdapter(sdrListAdapter);
    }

    //设置了列表项点击
    @覆盖
    保护无效onListItemClick(ListView的L,视图V,INT位置,长的id){
        super.onListItemClick(L,V,位置ID);
        //创建一个开关,使每个项目是不同的播放列表
        开关(位置){
        情况下0:
            意图BOJintent =新的意图(这一点,BOJAudioActivity.class);
            //创建一个使用PlaylistGroup的LocalActivityManager视图
            查看查看= PlaylistGroup.group.getLocalActivityManager()
            .startActivity(show_city,BOJintent
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .getDecorView();

            //再一次,更换视图
            PlaylistGroup.group.replaceView(视图);

         // playbackServiceIntentBOJ =新的意图(这一点,BOJAudioService.class);
                Log.d(TAG,MADE央行意图);
        // startService(playbackServiceIntentBOJ);
                Log.d(TAG,启动BOJ服务);

            打破;
        情况1:
            意图BOMintent =新的意图(这一点,BOMAudioActivity.class);
            //创建一个使用PlaylistGroup的LocalActivityManager视图
            查看视图2 = PlaylistGroup.group.getLocalActivityManager()
            .startActivity(show_city,BOMintent
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .getDecorView();

            //再一次,更换视图
           PlaylistGroup.group.replaceView(视图2);
                Log.d(TAG,替换视图);

                //getApplicationContext().stopService(playbackServiceIntentBOJ);

            // playbackServiceIntentBOM =新的意图(这一点,BOJAudioService.class);
                Log.d(TAG,制造BOM服务意向书);
        // startService(playbackServiceIntentBOM);
                Log.d(TAG,启动BOM服务);

                如果(DUBAudioActivity.isRunningDUB =真){
                    stopService(playbackServiceIntentDUB);
                    Log.d(TAG,一站式服务isRunningDUB);
                }
//
            打破;
        案例2:

            意图DUBIntent =新的意图(这一点,DUBAudioActivity.class);
            查看视图3 = PlaylistGroup.group.getLocalActivityManager()
                        .startActivity(show_city,DUBIntent
                                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                                .getDecorView();
            PlaylistGroup.group.replaceView(VIEW3);
                Log.d(TAG,替换视图);

            startService(playbackServiceIntentDUB);
                Log.d(TAG,启动DUB服务);

            打破;

        }


    }


}
 

服务类:

 公共类DUBAudioService扩展服务实现在preparedListener,OnCompletionListener {

吐司loadingMessage;

私有静态最后字符串变量= DUBAudioService.class.getSimpleName();

    公共静态布尔isRunningDUB = FALSE;

    //跟踪播放列表项的
    矢量< PlaylistFile> playlistItems;

    MediaPlayer的媒体播放器;

    字符串的baseUrl =;

    //跟踪哪些项目,从我们的矢量
    INT currentPlaylistltemNumber = 0;

    公共类DUBBackgroundAudioServiceBinder扩展粘合剂{
        DUBAudioService的getService(){
        返回DUBAudioService.this;
        }
    }

    私人最终的IBinder basBinderDUB =新DUBBackgroundAudioServiceBinder();



    @覆盖
    公众的IBinder onBind(意向意图){
        返回basBinderDUB;
    }

    @覆盖
    公共无效的onCreate(){
        Log.v(PLAYERSERVICE,的onCreate);
        媒体播放器=新的MediaPlayer();
        新MusicAsync()执行()。
            Log.d(TAG,execute'd异步);
        mediaPlayer.setOn preparedListener(本);
            Log.d(TAG,在prepared监听器设置);
        mediaPlayer.setOnCompletionListener(本);
            Log.d(TAG,在完成监听器设置);

            isRunningDUB = TRUE;
            Log.d(TAG,isRunningRUB =真正的);
    }

    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        //如果(!mediaPlayer.isPlaying()){
        // mediaPlayer.start();
        //}
        返回START_STICKY;
    }


    类MusicAsync扩展的AsyncTask<虚空,虚空,虚空> {
        @覆盖
        在preExecute保护无效(){
        }
        @覆盖
        保护无效doInBackground(虚空......为arg0){
            // TODO自动生成方法存根

            //创建空载体
            playlistItems =新矢量< PlaylistFile>();

            // HTTP客户端库
            HttpClient的HttpClient的=新DefaultHttpClient();
            HTTPGET调用getRequest =新HTTPGET(http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u); //我想你可以添加M3U东西在这里

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

            尝试 {
            HTT presponse HTT presponse = httpClient.execute(调用getRequest);
            如果(HTT presponse.getStatusLine()的getStatus code()!= HttpStatus.SC_OK){
            // 错误信息
            Log.v(HTTP错误,HTT presponse.getStatusLine()getReasonPhrase());
            }
            其他 {
                InputStream中的InputStream = HTT presponse.getEntity()的getContent()。
                BufferedReader中的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中));

                串线;
                而((行= bufferedReader.readLine())!= NULL){
                    Log.v(PLAYLISTLINE,弊+线);

                    如果(line.startsWith(#)){
                        //元数据
                        //可以做更多与此,但现在不是FO
                    }否则如果(line.length()大于0){
                        字符串文件路径=;
                            如果(line.startsWith(HTTP://)){
                            //假定它是一个完整的URL
                                文件路径=行;
                            } 其他 {
                            //假定它是相对的
                            文件路径= getRequest.getURI()解析(线)的ToString()。
                            }

                            PlaylistFile playlistFile =新PlaylistFile(文件路径);
                            playlistItems.add(playlistFile);
                            }
                            }
                            inputStream.close();
                            }
                            }赶上(ClientProtocolException E){
                                e.printStackTrace();
                            }赶上(IOException异常E){
                            即的printStackTrace();
                            }


                            currentPlaylistltemNumber = 0;
                            如果(playlistItems.size()大于0)
                            {
                            字符串路径=((PlaylistFile)playlistItems.get(currentPlaylistltemNumber))getFilePath()。
                            尝试 {
                                mediaPlayer.setDataSource(路径);

                            。媒体播放器prepareAsync();}
                            赶上(抛出:IllegalArgumentException E)
                            {e.printStackTrace();
                            }赶上(IllegalStateException异常E){
                                e.printStackTrace();
                            }赶上(IOException异常E){
                            e.printStackTrace();}
                            }



            返回null;
        }
        //
        保护无效onPostExecute(无效的结果){
            //为playButton。的setEnabled(假);
        }
    }



    @覆盖
    公共无效ONSTART(意向意图,诠释startId){
        super.onStart(意向,startId);


    }

    公共无效的onDestroy(){
        如果(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            Log.d(TAG,乐stopp'd);
        }
        //mediaPlayer.release();
        Log.d(TAG的onDestroy);
    }

    @覆盖
    在prepared公共无效(MediaPlayer的媒体播放器){
        // TODO自动生成方法存根\
        Log.d(TAG,音乐是prepared,将启动);
        mediaPlayer.start();
    }

    公共无效onCompletion(MediaPlayer的_mediaPlayer){
        Log.d(TAG,宋完成,下一首歌);
        mediaPlayer.stop();
        mediaPlayer.reset();
            如果(playlistItems.size()> currentPlaylistltemNumber + 1){
                currentPlaylistltemNumber ++;
            字符串路径=
                ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber))getFilePath();
                尝试 {
                    mediaPlayer.setDataSource(路径);
                    。媒体播放器prepareAsync();
                }赶上(抛出:IllegalArgumentException E){
                    即的printStackTrace();
                }赶上(IllegalStateException异常E){
                    e.printStackTrace();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
    }

    类PlaylistFile {
        字符串文件路径;
            公共PlaylistFile(字符串_filePath){
                文件路径= _filePath;
            }
            公共无效setFilePath(字符串_filePath){
                文件路径= _filePath;
            }
            公共字符串getFilePath(){
                返回文件路径;
            }
        }


    公共无效playSong(){
        Log.d(TAG,start'd);
        mediaPlayer.start();
    }

    公共无效pauseSong(){
        Log.d(TAG,pause'd);
        mediaPlayer.pause();
    }



}
 

解决方案

这得到pretty的复杂,但我用下面来看看我的服务正在运行:

 私人布尔isMyServiceRunning(){
ActivityManager经理=(ActivityManager)getSystemService(ACTIVITY_SERVICE);
对于(RunningServiceInfo服务:manager.getRunningServices(Integer.MAX_VALUE的)){
    如果(com.example.MyService.equals(service.service.getClassName())){
        返回true;
    }
}
返回false;
}
 

我说这在我的列表视图类,并提出如果每个case语句,看它是否正在运行,如果是这样,将停止服务

我还做了我所有我结合conenctions公开,这样的列表视图类可以访问它们,并开始他们的点击。

如果有人想进一步了解,等我发短信。

I currently have a listview and when you click on an item it runs a service with a mediaplayer. If I click on another item in the listview the service that's running should stop and run the new service. I am using a boolean isRunning set to false and when the service is created it returns true. Then in the listview I call that flag in an if statement. However, its not exactly working. I think I may be doing this wrong. Any ideas?

This probably sounds confusing the way I described it so Here is the code to my listview and my service. I am only testing this on case 3 (so I press this item to start the service and then click on case 2 to see if it will stop it).

Listview class:

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;

        }


    }


}

Service Class:

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();
    }



}

解决方案

This gets pretty complicated but I used the following to see if my service was running:

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;
}

I added this in my listview class and put if statements in each case to see if it was running and if so would stop the service.

I also made my all of my binding conenctions public so that the listview class could access them and start them on click.

If anyone wants to further understand, etc message me.

这篇关于Android-列表视图,服务媒体播放器,以及布尔标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆