欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android開啟新線程播放背景音樂

 更新時間:2017年12月26日 10:09:21   作者:光仔December  
這篇文章主要為大家詳細介紹了Android開啟新線程播放背景音樂,具有一定的參考價值,感興趣的小伙伴們可以參考一下

在本實例用,開啟一個新的線程播放背景音樂,在音樂文件播放完畢后,暫停5秒后重新開始播放。

具體實現:

界面(只有一個"開始"按鈕)
res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:id="@+id/linearLayout1" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical" > 
 
 
  <Button 
   android:id="@+id/button1" 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:text="開始" /> 
 
 
</LinearLayout> 

在res/文件夾下創(chuàng)建raw目錄,在raw/下放置需要播放的背景音樂文件(這里放置的是flower.mp3文件)

MainActivity:

package com.example.test; 
 
import android.app.Activity; 
import android.media.MediaPlayer; 
import android.media.MediaPlayer.OnCompletionListener; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
 
public class MainActivity extends Activity{ 
 private Thread thread;//聲明一個線程對象 
 private static MediaPlayer mp=null;//聲明一個MediaPlayer對象 
 @Override 
 public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main); 
   
  Button startButton=(Button)findViewById(R.id.button1);//獲取開始按鈕 
  startButton.setOnClickListener(new OnClickListener() { 
    
   @Override 
   public void onClick(View v) { 
     ((Button)v).setEnabled(false);//設置按鈕不可用 
     //創(chuàng)建一個用于播放背景音樂的線程 
     thread=new Thread(new Runnable(){ 
 
 
     @Override 
     public void run() { 
      playBGSound();//播放背景音樂 
       
     } 
 
 
     }); 
     thread.start();//開啟線程 
   } 
  }); 
   
 } 
 
 
 private void playBGSound() { 
  if(mp!=null){ 
   mp.release();//釋放資源 
  } 
  mp=MediaPlayer.create(MainActivity.this, R.raw.flower); 
  mp.start(); 
  //為MediaPlayer添加播放完成事件監(jiān)聽 
  mp.setOnCompletionListener(new OnCompletionListener() { 
    
   @Override 
   public void onCompletion(MediaPlayer mp) { 
    try { 
     Thread.sleep(5000);//讓線程休眠5秒 
     <span style="white-space:pre">   </span>playBGSound();//重新播放音樂 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
     
   } 
  }); 
 } 
 
 
 @Override 
 protected void onDestroy() { 
  if(mp!=null){ 
   mp.stop(); 
   mp.release(); 
   mp=null; 
  } 
  if(thread!=null){ 
   thread=null; 
  } 
  super.onDestroy(); 
 } 
 
 
} 

 運行結果:點擊開始按鈕,按鈕將變成不可用狀態(tài),并且開始播放背景音樂,界面如圖

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論