2016-01-22 489 views
5

我在我的服務器中創建了一個XML文件。它包含titlelink標籤。我獲取標籤並將其顯示爲ListView中的鏈接。從那裏當用戶點擊鏈接,然後我想播放電臺應用程序中的.pls文件。如何在Android中播放在線廣播流媒體網址。如何在android中播放.pls廣播流媒體url

這裏是我的XML文件:

<item> 
    <title> Kushi FM </title> 
    <link>http://108.163.197.114:8071/listen.pls</link> 
</item> 

我不知道怎麼玩的下一個活動的鏈接。

MainActivity

public class MainActivity extends AppCompatActivity { 
    // All static variables 
    static final String URL1 = "http://servernmae.com/stations"; 
    // XML node keys 
    static final String KEY_ITEM = "item"; // parent node 
    static final String KEY_TITLE = "title"; 
    static final String KEY_LINK = "link"; 
    URL url; 

    URLConnection urlConnection; 
    //Context context; 
    ListView listview; 
    int images=R.drawable.radio; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // isNetworkAvailable(this); 

     listview = (ListView) findViewById(R.id.list); 

     if(isNetworkAvailable(this)) 
     { 
      new GetData().execute(); 

     }else { 
      Toast.makeText(getApplicationContext(), "Please Connect to Internet and Check Again ! Thanks)", 
        Toast.LENGTH_LONG).show(); 
     } 



    } 
    private boolean isNetworkAvailable(Context context) { 
     ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     if (connectivity != null) { 
      NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
      if (info != null) { 
       for (int i = 0; i < info.length; i++) { 
        Log.w("INTERNET:",String.valueOf(i)); 
        if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
         Log.w("INTERNET:", "connected!"); 
         return true; 
        } 
       } 
      } 
     } 
     return false; 
    } 

    class GetData extends AsyncTask<String, String, String> { 
     String xml = "error"; 

     @Override 
     protected String doInBackground(String... params) { 

      try { 
       url = new URL(URL1); 

       urlConnection = (HttpURLConnection) url.openConnection(); 

       InputStream in = urlConnection.getInputStream(); 

       InputStreamReader isw = new InputStreamReader(in); 

       BufferedReader br = new BufferedReader(isw); 
       StringBuilder sb = new StringBuilder(); 
       String line; 
       while ((line = br.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       br.close(); 

       xml = sb.toString(); 
      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 


      return xml; 
     } 


     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 

      final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); 
      ArrayList<String> title= new ArrayList<>(); 
      //title.add(""); 

      Document doc = null; 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      try { 

       DocumentBuilder db = dbf.newDocumentBuilder(); 

       InputSource is = new InputSource(); 
       is.setCharacterStream(new StringReader(xml)); 
       doc = db.parse(is); 


       NodeList nl = doc.getElementsByTagName(KEY_ITEM); 
       for (int i = 0; i < nl.getLength(); i++) { 
        HashMap<String, String> map = new HashMap<String, String>(); 
        Element e = (Element) nl.item(i); 
        Log.e("TAg1", getValue(e, KEY_TITLE)); 
        //Log.e("TAg2", getValue(e, KEY_LINK)); 
        map.put(KEY_TITLE, getValue(e, KEY_TITLE)); 
        map.put(KEY_LINK, getValue(e, KEY_LINK)); 
        menuItems.add(map); 

        title.add(getValue(e, KEY_TITLE)); 
       } 


      } catch (ParserConfigurationException e) { 
       Log.e("Error: ", e.getMessage()); 
      } catch (SAXException e) { 
       Log.e("Error: ", e.getMessage()); 
      } catch (IOException e) { 
       Log.e("Error: ", e.getMessage()); 

      } 
      String[] dataArr = new String[title.size()]; 
      dataArr = title.toArray(dataArr); 
      CustomAdapter adapter = new CustomAdapter(getApplicationContext(), dataArr); 
      listview.setAdapter(adapter); 
      listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        //HashMap<String, String> selectedMap = menuItems.get(position); 
        HashMap<String,String> selectedMap= menuItems.get(position); 
        String urls = selectedMap.get(KEY_LINK); 
        Intent intent = new Intent(MainActivity.this, Service_Player.class); 
        intent.putExtra("url",urls); 
        startActivity(intent); 

       } 

      }); 




     } 

     public final String getElementValue(Node elem) { 
      Node child; 
      if (elem != null) { 
       if (elem.hasChildNodes()) { 
        for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { 
         if (child.getNodeType() == Node.TEXT_NODE) { 
          return child.getNodeValue(); 
         } 
        } 
       } 
      } 
      return ""; 
     } 

     public String getValue(Element item, String str) { 
      NodeList n = item.getElementsByTagName(str); 
      return this.getElementValue(n.item(0)); 
     } 


    } 

Service_player.java

public class Service_Player extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_service__player); 
     startService(new Intent(this, MediaPlayerService.class)); 
     String url = getIntent().getStringExtra("url"); 
     if (!TextUtils.isEmpty(url)) 
      startMediaPlayer(url); 


    } 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     registerReceiver(receiverFromservice, new IntentFilter(MediaPlayerService.SERVICE_TO_ACTIVITY)); 
    } 

    private String currentPlayerStatus = "N/A"; 
    private BroadcastReceiver receiverFromservice = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (MediaPlayerService.SERVICE_TO_ACTIVITY.equalsIgnoreCase(action)) { 
       /* 
       * To get current status of player 
       * */ 
       currentPlayerStatus = intent.getStringExtra(MediaPlayerService.PLAYER_STATUS_KEY); 
       Log.e("Player Mode", "" + currentPlayerStatus); 
      } 
     } 
    }; 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     unregisterReceiver(receiverFromservice); 
    } 
    public void startMediaPlayer(String url) { 
     Intent intent = new Intent(); 
     intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
     intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PLAY_MEDIA_PLAYER); 
     intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, url); 
     sendBroadcast(intent); 
} 

MediaPlayerService.java

public class MediaPlayerService extends Service { 

    public static final String BROADCAST_TO_SERVICE = "com.mediaplayer.playerfunction"; 
    public static final String SERVICE_TO_ACTIVITY = "com.mediaplayer.currentPlayerStatus"; 
    public static final String PLAYER_FUNCTION_TYPE = "playerfunction"; 
    public static final String PLAYER_TRACK_URL = "trackURL"; 
    public static final int PLAY_MEDIA_PLAYER = 1; 
    public static final int PAUSE_MEDIA_PLAYER = 2; 
    public static final int RESUME_MEDIA_PLAYER = 3; 
    public static final int STOP_MEDIA_PLAYER = 4; 
    public static final int CHANGE_PLAYER_TRACK = 5; 
    public static final String PLAYER_STATUS_KEY = "PlayerCurrentStatus"; 
    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     IntentFilter intentFilter = new IntentFilter(BROADCAST_TO_SERVICE); 
     registerReceiver(playerReceiver, intentFilter); 
     if (mPlayer != null && mPlayer.isPlaying()) { 
      sendPlayerStatus("playing"); 
     } 
     return START_STICKY; 
    } 

    private BroadcastReceiver playerReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (BROADCAST_TO_SERVICE.equalsIgnoreCase(action)) { 
       String trackURL = intent.hasExtra(PLAYER_TRACK_URL) ? intent.getStringExtra(PLAYER_TRACK_URL) : ""; 
       int function = intent.getIntExtra(PLAYER_FUNCTION_TYPE, 0); 
       switch (function) { 
        case CHANGE_PLAYER_TRACK: 
         changeTrack(trackURL); 
         break; 
        case STOP_MEDIA_PLAYER: 
         stopPlayer(); 
         break; 
        case PLAY_MEDIA_PLAYER: 
         startMediaPlayer(trackURL); 
         break; 
        case PAUSE_MEDIA_PLAYER: 
         pausePlayer(); 
         break; 
        case RESUME_MEDIA_PLAYER: 
         resumePlayer(); 
         break; 
       } 

      } 
     } 
    }; 
    private MediaPlayer mPlayer; 

    private void pausePlayer() { 
     if (mPlayer != null && mPlayer.isPlaying()) { 
      mPlayer.pause(); 
      sendPlayerStatus("pause"); 
     } 
    } 

    private void resumePlayer() { 
     if (mPlayer != null && !mPlayer.isPlaying()) { 
      mPlayer.start(); 
      sendPlayerStatus("playing"); 
     } 
    } 

    private void changeTrack(String url) { 
     stopPlayer(); 
     startMediaPlayer(url); 

    } 

    private void stopPlayer() { 
     if (mPlayer != null) { 
      mPlayer.stop(); 
      mPlayer.release(); 
      mPlayer = null; 
      sendPlayerStatus("stopped"); 

     } 
    } 

    public void startMediaPlayer(String url) { 
     if (TextUtils.isEmpty(url)) 
      return; 
     if (mPlayer == null) 
      mPlayer = new MediaPlayer(); 
     try { 
      mPlayer.setDataSource(url); 
      mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { 

       @Override 
       public boolean onError(MediaPlayer mp, int what, int extra) { 
        if (extra == MediaPlayer.MEDIA_ERROR_SERVER_DIED 
          || extra == MediaPlayer.MEDIA_ERROR_MALFORMED) { 
         sendPlayerStatus("erroronplaying"); 
        } else if (extra == MediaPlayer.MEDIA_ERROR_IO) { 
         sendPlayerStatus("erroronplaying"); 
         return false; 
        } 
        return false; 
       } 
      }); 
      mPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { 

       public void onBufferingUpdate(MediaPlayer mp, int percent) { 
        Log.e("onBufferingUpdate", "" + percent); 

       } 
      }); 
      mPlayer.prepareAsync(); 
      mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 

       public void onPrepared(MediaPlayer mp) { 
        mPlayer.start(); 
        sendPlayerStatus("playing"); 
       } 
      }); 
      mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 

       @Override 
       public void onCompletion(MediaPlayer mp) { 
        Log.e("onCompletion", "Yes"); 
        sendPlayerStatus("completed"); 
       } 
      }); 
      mPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() { 
       @Override 
       public boolean onInfo(MediaPlayer mp, int what, int extra) { 
        return false; 
       } 
      }); 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
     } catch (IllegalStateException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private void sendPlayerStatus(String status) { 
     Intent intent = new Intent(); 
     intent.setAction(SERVICE_TO_ACTIVITY); 
     intent.putExtra(PLAYER_STATUS_KEY, status); 
     sendBroadcast(intent); 
    } 

Manifest.xml

<!-- Internet Permissions --> 
    <uses-permission android:name="android.permission.INTERNET" /> 

    <!-- Network State Permissions --> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name=".Service_Player" 
      android:label="@string/title_activity_service__player" > 
     </activity> 
     <service android:name=".MediaPlayerService"></service> 
    </application> 

回答

0
MediaPlayer mp; 
mp=MediaPlayer.create(getApplicationContext(),Uri.parse(url)) 
//Example url of .pls file http://50.xx.xxx.xx:xx40/) 

mp.start(); 
mp.pause(); 
mp.release() (or mp.reset() as applicable) 
3

我會建議你使用Service如果要創建與MediaPlayer的流或正常MediaPlayer的應用。集中處理播放器背景&會很容易。

要使用媒體播放器的服務,您可以用BroadCastReceiver或綁定的服務,按您的requirement.It使用這將是一件好事,如果MediaPlayer的相關服務,如果你把它running in foreground在這裏下面的代碼我還沒有辦理請檢查給定的鏈接。

在示例代碼中,我已經使用BroadCast Receiver從Activity發送命令到MediaPlayer的服務(如播放,暫停,更改曲目等),反之亦然。

現在要獲取您從Activity onItemClickListner發送的url,您需要從Intent獲取。

String url = getIntent().getStringExtra("url"); 

PlayerScreen

public class PlayerScreen extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.player); 
     startService(new Intent(this, MediaPlayerService.class)); 
     findViewById(R.id.btnChangeTrack).setOnClickListener(clickListener); 
     findViewById(R.id.btnStartMediaPlayer).setOnClickListener(clickListener); 
     findViewById(R.id.btnStopMediaPlayer).setOnClickListener(clickListener); 
     ToggleButton toggleButton = (ToggleButton) findViewById(R.id.togglePauseResume); 
     toggleButton.setOnCheckedChangeListener(checkedChangeListener); 
     /* 
     * To get url which is passing from the previous activity listitem click. 
     * If url which is pass from listitem click is not empty it will start player 
     * */ 
     String url = getIntent().getStringExtra("url"); 
     if (!TextUtils.isEmpty(url)) 
      startMediaPlayer(url); 

    } 

    private ToggleButton.OnCheckedChangeListener checkedChangeListener = new ToggleButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (!isChecked) { 
       Intent intent = new Intent(); 
       intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
       intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PAUSE_MEDIA_PLAYER); 
       sendBroadcast(intent); 
      } else { 
       Intent intent = new Intent(); 
       intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
       intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.RESUME_MEDIA_PLAYER); 
       sendBroadcast(intent); 
      } 
     } 
    }; 
    private View.OnClickListener clickListener = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent; 
      switch (v.getId()) { 
       case R.id.btnChangeTrack: 
        intent = new Intent(); 
        intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
        intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.CHANGE_PLAYER_TRACK); 
        intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, "http://69.64.41.64:9938"); 
        sendBroadcast(intent); 
        break; 
       case R.id.btnStartMediaPlayer: 
        startMediaPlayer("http://108.163.197.114:8071/listen.pls"); 
        break; 
       case R.id.btnStopMediaPlayer: 
        intent = new Intent(); 
        intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
        intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.STOP_MEDIA_PLAYER); 
        sendBroadcast(intent); 
        break; 

      } 
     } 
    }; 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     registerReceiver(receiverFromservice, new IntentFilter(MediaPlayerService.SERVICE_TO_ACTIVITY)); 
    } 

    private String currentPlayerStatus = "N/A"; 
    private BroadcastReceiver receiverFromservice = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (MediaPlayerService.SERVICE_TO_ACTIVITY.equalsIgnoreCase(action)) { 
       /* 
       * To get current status of player 
       * */ 
       currentPlayerStatus = intent.getStringExtra(MediaPlayerService.PLAYER_STATUS_KEY); 
       Log.e("Player Mode", "" + currentPlayerStatus); 
      } 
     } 
    }; 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     unregisterReceiver(receiverFromservice); 
    } 

    /** 
    * TO start media player.It will send broadcast to Service & from service player will start 
    * 
    * @param url 
    */ 
    public void startMediaPlayer(String url) { 
     Intent intent = new Intent(); 
     intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
     intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PLAY_MEDIA_PLAYER); 
     intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, url); 
     sendBroadcast(intent); 
    } 
} 

MediaPlayerService

public class MediaPlayerService extends Service { 
    public static final String BROADCAST_TO_SERVICE = "com.mediaplayer.playerfunction"; 
    public static final String SERVICE_TO_ACTIVITY = "com.mediaplayer.currentPlayerStatus"; 
    public static final String PLAYER_FUNCTION_TYPE = "playerfunction"; 
    public static final String PLAYER_TRACK_URL = "trackURL"; 
    public static final int PLAY_MEDIA_PLAYER = 1; 
    public static final int PAUSE_MEDIA_PLAYER = 2; 
    public static final int RESUME_MEDIA_PLAYER = 3; 
    public static final int STOP_MEDIA_PLAYER = 4; 
    public static final int CHANGE_PLAYER_TRACK = 5; 
    public static final String PLAYER_STATUS_KEY = "PlayerCurrentStatus"; 

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

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     IntentFilter intentFilter = new IntentFilter(BROADCAST_TO_SERVICE); 
     registerReceiver(playerReceiver, intentFilter); 
     if (mPlayer != null && mPlayer.isPlaying()) { 
      sendPlayerStatus("playing"); 
     } 
     return START_STICKY; 
    } 

    private BroadcastReceiver playerReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (BROADCAST_TO_SERVICE.equalsIgnoreCase(action)) { 
       String trackURL = intent.hasExtra(PLAYER_TRACK_URL) ? intent.getStringExtra(PLAYER_TRACK_URL) : ""; 
       int function = intent.getIntExtra(PLAYER_FUNCTION_TYPE, 0); 
       switch (function) { 
        case CHANGE_PLAYER_TRACK: 
         changeTrack(trackURL); 
         break; 
        case STOP_MEDIA_PLAYER: 
         stopPlayer(); 
         break; 
        case PLAY_MEDIA_PLAYER: 
         startMediaPlayer(trackURL); 
         break; 
        case PAUSE_MEDIA_PLAYER: 
         pausePlayer(); 
         break; 
        case RESUME_MEDIA_PLAYER: 
         resumePlayer(); 
         break; 
       } 

      } 
     } 
    }; 
    private MediaPlayer mPlayer; 

    private void pausePlayer() { 
     if (mPlayer != null && mPlayer.isPlaying()) { 
      mPlayer.pause(); 
      sendPlayerStatus("pause"); 
     } 
    } 

    private void resumePlayer() { 
     if (mPlayer != null && !mPlayer.isPlaying()) { 
      mPlayer.start(); 
      sendPlayerStatus("playing"); 
     } 
    } 

    private void changeTrack(String url) { 
     stopPlayer(); 
     startMediaPlayer(url); 

    } 

    private void stopPlayer() { 
     if (mPlayer != null) { 
      mPlayer.stop(); 
      mPlayer.release(); 
      mPlayer = null; 
      sendPlayerStatus("stopped"); 

     } 
    } 

    public void startMediaPlayer(String url) { 
     if (TextUtils.isEmpty(url)) 
      return; 
     if (mPlayer == null) 
      mPlayer = new MediaPlayer(); 
     try { 
      mPlayer.setDataSource(url); 
      mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { 

       @Override 
       public boolean onError(MediaPlayer mp, int what, int extra) { 
        if (extra == MediaPlayer.MEDIA_ERROR_SERVER_DIED 
          || extra == MediaPlayer.MEDIA_ERROR_MALFORMED) { 
         sendPlayerStatus("erroronplaying"); 
        } else if (extra == MediaPlayer.MEDIA_ERROR_IO) { 
         sendPlayerStatus("erroronplaying"); 
         return false; 
        } 
        return false; 
       } 
      }); 
      mPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { 

       public void onBufferingUpdate(MediaPlayer mp, int percent) { 
        Log.e("onBufferingUpdate", "" + percent); 

       } 
      }); 
      mPlayer.prepareAsync(); 
      mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 

       public void onPrepared(MediaPlayer mp) { 
        mPlayer.start(); 
        sendPlayerStatus("playing"); 
       } 
      }); 
      mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 

       @Override 
       public void onCompletion(MediaPlayer mp) { 
        Log.e("onCompletion", "Yes"); 
        sendPlayerStatus("completed"); 
       } 
      }); 
      mPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() { 
       @Override 
       public boolean onInfo(MediaPlayer mp, int what, int extra) { 
        return false; 
       } 
      }); 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
     } catch (IllegalStateException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private void sendPlayerStatus(String status) { 
     Intent intent = new Intent(); 
     intent.setAction(SERVICE_TO_ACTIVITY); 
     intent.putExtra(PLAYER_STATUS_KEY, status); 
     sendBroadcast(intent); 
    } 
} 

球員。XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:id="@+id/section_label" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/ab_tool" 
     android:text="Home" /> 

    <Button 
     android:id="@+id/btnStartMediaPlayer" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/section_label" 
     android:text="Start Player" /> 


    <ToggleButton 
     android:id="@+id/togglePauseResume" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/btnStartMediaPlayer" 
     android:checked="true" 
     android:textOff="Resume" 
     android:textOn="Pause" /> 

    <Button 
     android:id="@+id/btnChangeTrack" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/togglePauseResume" 
     android:text="Chanage Track" /> 

    <Button 
     android:id="@+id/btnStopMediaPlayer" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/btnChangeTrack" 
     android:text="STOP" /> 
</RelativeLayout> 

清單

<activity android:name=".PlayerScreen"> 

    <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 


     <category android:name="android.intent.category.LAUNCHER" /> 
    </intent-filter> 
</activity> 
<service android:name=".MediaPlayerService"></service> 

從流網址頭數據可以獲取數據0

對於這裏測試的目的我用兩個URL

UPDATE PlayerActivity

public class PlayerScreen extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.player); 
     startService(new Intent(this, MediaPlayerService.class)); 
     /* 
     * To get url which is passing from the previous activity listitem click. 
     * If url which is pass from listitem click is not empty it will start player 
     * */ 
     String url = getIntent().getStringExtra("url"); 
     if (!TextUtils.isEmpty(url)) 
      startMediaPlayer(url); 

    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     registerReceiver(receiverFromservice, new IntentFilter(MediaPlayerService.SERVICE_TO_ACTIVITY)); 
    } 

    private String currentPlayerStatus = "N/A"; 
    private BroadcastReceiver receiverFromservice = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (MediaPlayerService.SERVICE_TO_ACTIVITY.equalsIgnoreCase(action)) { 
       /* 
       * To get current status of player 
       * */ 
       currentPlayerStatus = intent.getStringExtra(MediaPlayerService.PLAYER_STATUS_KEY); 
       Log.e("Player Mode", "" + currentPlayerStatus); 
      } 
     } 
    }; 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     unregisterReceiver(receiverFromservice); 
    } 

    /** 
    * TO start media player.It will send broadcast to Service & from service player will start 
    * 
    * @param url 
    */ 
    public void startMediaPlayer(String url) { 
     Intent intent = new Intent(); 
     intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE); 
     intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PLAY_MEDIA_PLAYER); 
     intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, url); 
     sendBroadcast(intent); 
    } 
} 

讓我知道什麼。

+0

感謝但當用戶在列表視圖中單擊Fm名稱下一個活動將自動播放我們該如何做? – vasanth

+0

下面是我在NextActivity中編寫的代碼是否正確? Intent intent = getIntent(); final String selectedData = intent.getStringExtra(「url」); fmname.setText(selectedData); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(selectedData); mMediaPlayer.prepareAsync(); mMediaPlayer.setOnPreparedListener(新MediaPlayer.OnPreparedListener(){ 公共無效onPrepared(MediaPlayer的熔點){ mMediaPlayer.start();} }); – vasanth

+0

'Player'我的答案中的活動將是'Player'活動的'onCreate'方法中的'Service_Player',它將從意圖獲取url數據並調用'startMediaPlayer'方法,該方法將啓動播放器 – user1140237