溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android使用Service實現(xiàn)簡單音樂播放實例

發(fā)布時間:2020-10-14 18:18:08 來源:腳本之家 閱讀:180 作者:cjjky 欄目:移動開發(fā)

      Service翻譯成中文是服務(wù),熟悉Windows 系統(tǒng)的同學(xué)一定很熟悉了。Android里的Service跟Windows里的Service功能差不多,就是一個不可見的進程在后臺執(zhí)行。

      Android中的服務(wù),它與Activity不同,它是不能與用戶交互的,不能自己啟動的,運行在后臺的程序,如果我們退出應(yīng)用時,Service進程并沒有結(jié)束,它仍然在后臺運行,例如我們打開一個音樂播放器來聽音樂,在聽音樂的同時也想做下其它的事情,比如上網(wǎng)聊Q、或者上網(wǎng)瀏覽新聞之類的事情。這樣的話,我們就需要用到Service服務(wù)了。下面我們以一個簡單的音樂播放器的實例來說明下Service的生命周期和Service的使用。

下面是音樂播放器Demo的程序結(jié)構(gòu)圖:

Android使用Service實現(xiàn)簡單音樂播放實例

Android Service 的生命周期:

Android中Service的生命周期并不是很復(fù)雜,只是繼承了onCreate(), onStart(), onDestory()三個方法。當(dāng)我們第一次啟動Service服務(wù)時,調(diào)用onCreate() --> onStart()兩個方法,當(dāng)停止Service服務(wù)時,調(diào)用onDestory()方法。如果Service已經(jīng)啟動了,第二次再啟動同一個服務(wù)時,就只是調(diào)用 onStart() 這個方法了。

Android Service 的使用:

[1] 參照上面的程序結(jié)構(gòu)圖,我們可以創(chuàng)建一個Android程序,在src目錄下創(chuàng)建一個Activity,一個繼承自Service類的服務(wù)類;同時在資源文件夾res目錄下創(chuàng)建一個raw的文件夾存放音頻文件,如把music.mp3音樂文件放在該目錄下。該程序的主界面如下:

Android使用Service實現(xiàn)簡單音樂播放實例

[2] layout目錄下的main.xml文件的源碼:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  > 
  <TextView  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="Welcome to Andy's blog!" 
    android:textSize="16sp"/>   
  <TextView  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="音樂播放服務(wù)"/> 
  <Button 
    android:id="@+id/startMusic"  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="開啟音樂播放服務(wù)"/> 
  <Button 
    android:id="@+id/stopMusic"  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="停止音樂播放服務(wù)"/> 
  <Button 
   android:id="@+id/bindMusic"  
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:text="綁定音樂播放服務(wù)"/> 
  <Button 
   android:id="@+id/unbindMusic"  
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:text="解除 ——綁定音樂播放服務(wù)"/> 
</LinearLayout> 

[3] src目錄下MusicService.java源碼:

package com.andyidea.service; 
import android.app.Service; 
import android.content.Intent; 
import android.media.MediaPlayer; 
import android.os.IBinder; 
import android.util.Log; 
import android.widget.Toast; 
public class MusicService extends Service { 
  //為日志工具設(shè)置標(biāo)簽 
  private static String TAG = "MusicService"; 
  //定義音樂播放器變量 
  private MediaPlayer mPlayer; 
   
  //該服務(wù)不存在需要被創(chuàng)建時被調(diào)用,不管startService()還是bindService()都會啟動時調(diào)用該方法 
  @Override 
  public void onCreate() { 
    Toast.makeText(this, "MusicSevice onCreate()" 
        , Toast.LENGTH_SHORT).show(); 
    Log.e(TAG, "MusicSerice onCreate()"); 
     
    mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music); 
    //設(shè)置可以重復(fù)播放 
    mPlayer.setLooping(true); 
    super.onCreate(); 
  } 
   
  @Override 
  public void onStart(Intent intent, int startId) { 
    Toast.makeText(this, "MusicSevice onStart()" 
        , Toast.LENGTH_SHORT).show(); 
    Log.e(TAG, "MusicSerice onStart()"); 
     
    mPlayer.start(); 
     
    super.onStart(intent, startId); 
  } 
  @Override 
  public void onDestroy() { 
    Toast.makeText(this, "MusicSevice onDestroy()" 
        , Toast.LENGTH_SHORT).show(); 
    Log.e(TAG, "MusicSerice onDestroy()"); 
     
    mPlayer.stop(); 
     
    super.onDestroy(); 
  } 
  //其他對象通過bindService 方法通知該Service時該方法被調(diào)用 
  @Override 
  public IBinder onBind(Intent intent) { 
    Toast.makeText(this, "MusicSevice onBind()" 
        , Toast.LENGTH_SHORT).show(); 
    Log.e(TAG, "MusicSerice onBind()"); 
     
    mPlayer.start(); 
     
    return null; 
  } 
  //其它對象通過unbindService方法通知該Service時該方法被調(diào)用 
  @Override 
  public boolean onUnbind(Intent intent) { 
    Toast.makeText(this, "MusicSevice onUnbind()" 
        , Toast.LENGTH_SHORT).show(); 
    Log.e(TAG, "MusicSerice onUnbind()"); 
     
    mPlayer.stop(); 
     
    return super.onUnbind(intent); 
  } 
   
} 

[4] src目錄下MusicServiceActivity源碼:

package com.andyidea.service; 
import android.app.Activity; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.Toast; 
public class MusicServiceActivity extends Activity { 
   
  //為日志工具設(shè)置標(biāo)簽 
  private static String TAG = "MusicService"; 
   
  /** Called when the activity is first created. */ 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
     
    //輸出Toast消息和日志記錄 
    Toast.makeText(this, "MusicServiceActivity", 
        Toast.LENGTH_SHORT).show(); 
    Log.e(TAG, "MusicServiceActivity"); 
     
    initlizeViews(); 
  } 
   
  private void initlizeViews(){ 
    Button btnStart = (Button)findViewById(R.id.startMusic); 
    Button btnStop = (Button)findViewById(R.id.stopMusic); 
    Button btnBind = (Button)findViewById(R.id.bindMusic); 
    Button btnUnbind = (Button)findViewById(R.id.unbindMusic); 
     
    //定義點擊監(jiān)聽器 
    OnClickListener ocl = new OnClickListener() { 
       
      @Override 
      public void onClick(View v) { 
        //顯示指定 intent所指的對象是個  service 
        Intent intent = new Intent(MusicServiceActivity.this,MusicService.class); 
        switch(v.getId()){ 
        case R.id.startMusic: 
          //開始服務(wù) 
          startService(intent); 
          break; 
        case R.id.stopMusic: 
          //停止服務(wù) 
          stopService(intent); 
          break; 
        case R.id.bindMusic: 
          //綁定服務(wù) 
          bindService(intent, conn, Context.BIND_AUTO_CREATE); 
          break; 
        case R.id.unbindMusic: 
          //解綁服務(wù) 
          unbindService(conn); 
          break; 
        } 
      } 
    }; 
     
     //綁定點擊監(jiān)聽 
    btnStart.setOnClickListener(ocl); 
    btnStop.setOnClickListener(ocl); 
    btnBind.setOnClickListener(ocl); 
    btnUnbind.setOnClickListener(ocl); 
  } 
   
  //定義服務(wù)鏈接對象 
  final ServiceConnection conn = new ServiceConnection() { 
     
    @Override 
    public void onServiceDisconnected(ComponentName name) { 
      Toast.makeText(MusicServiceActivity.this, "MusicServiceActivity onSeviceDisconnected" 
          , Toast.LENGTH_SHORT).show(); 
      Log.e(TAG, "MusicServiceActivity onSeviceDisconnected"); 
    } 
     
    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
      Toast.makeText(MusicServiceActivity.this, "MusicServiceActivity onServiceConnected" 
          ,Toast.LENGTH_SHORT).show(); 
      Log.e(TAG, "MusicServiceActivity onServiceConnected"); 
    } 
  }; 
} 

[5] 最后,我們別忘了在AndroidManifest.xml配置文件中添加對Service的注冊。即在application節(jié)點中添加

 <service android:name=".MusicService"/> 進行注冊。

[6] 我們來看下程序運行后的Log.e中顯示的Service生命周期

Android使用Service實現(xiàn)簡單音樂播放實例

[7] 我們在Android終端設(shè)備中查看下剛才啟動的音樂播放服務(wù),看看我們退出程序后,是不是該程序的服務(wù)還在運行的呢?按如下步驟:Menu --> Settings --> Applications --> Running services 。在彈出的 Running services 中可以看到有哪些服務(wù)在運行。

Android使用Service實現(xiàn)簡單音樂播放實例

這樣我們就看到我們退出程序后,是由于該服務(wù)還在后臺運行著,所以我們的音樂還可以繼續(xù)播放著。就這樣,我們就可以一邊享受音樂,一邊可以聊QQ,或者瀏覽新聞等等。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI