2011-07-17 3 views
1

현재 저는 listview입니다. 항목을 클릭하면 에 mediaplayer이 실행됩니다. listview에있는 다른 항목을 클릭하면 실행중인 service이 중지되고 새로운 service을 실행해야합니다. booleanisRunning을 false로 설정하고 서비스가 만들어지면 true를 반환합니다. 그런 다음 listview에서 if 문에서 해당 플래그를 호출합니다. 그러나, 정확하게 작동하지 않습니다. 나는 이것이 틀릴 수도 있다고 생각한다. 어떤 아이디어?Android-listview, service mediaplayer 및 boolean 플래그

이것은 내가 설명한대로 혼란스럽게 들릴 것입니다. 여기 내 코드는 listview이고내는 service입니다. 케이스 3에 대해서만 테스트하고 있습니다. (서비스를 시작하려면이 항목을 누르고, 멈추는 지 확인하려면 케이스 2를 클릭하십시오.)

목록보기 클래스 :

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



} 
+1

동일한 문제가있는 동일한 보트 워크 북에 있습니다. 어떻게 레이아웃이 'ListView'처럼 보이는지 보여 주시겠습니까? –

답변

0

이 꽤 복잡해진다하지만 난 내 서비스가 실행되고 있는지 확인하려면 다음을 사용 : 각각의 경우에 문이 실행하고있는 경우 경우 볼 경우

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 수업이 추가 넣어 그래서 service을 멈출 것입니다.

필자도 바인딩 뷰를 공개적으로 사용하여 listview 클래스에 액세스하여 클릭시 시작할 수 있도록했습니다.

누군가 더 이해하고 싶다면, 등등 메시지를 보내주십시오.

0

앱이 상태가 아닌 서비스를 추적 할 수 있습니다.