안 드 로 이 드 음악 재생 사례 공유

본 논문 의 사례 는 안 드 로 이 드 음악 재생 사례 의 구체 적 인 실현 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
효과:

분석:
이전 글 의 구조 와 같 습 니 다.다만 우 리 는 여기에 음악 을 재생 하 는 조작 을 추가 해 야 합 니 다.
사실은 시스템 에서 음악 을 재생 하 는 API 를 호출 하 는 것 일 뿐 입 니 다.서비스 에 쓰 면 됩 니 다.

//     
private MediaPlayer player;

public void onCreate() {
  File file=new File(Environment.getExternalStorageDirectory(),"a.mp3");
  player =new MediaPlayer();
  try {
   //     
   player.setDataSource(file.getAbsolutePath());
  } catch (Exception e) {
   e.printStackTrace();
  } 
  Log.d("fanfan", "onCreate");
  super.onCreate();
 }


public int onStartCommand(Intent intent, int flags, int startId) {
  
  try {
   //         ,       ,      onPrepared  
   player.setOnPreparedListener(new OnPreparedListener() {
    @Override
    //             
    public void onPrepared(MediaPlayer arg0) {
     //    
     player.start();
    }
   });
   
   //    ,      
   //    ,              
   player.prepareAsync();
   
  } catch (Exception e) {
   e.printStackTrace();
  } 
  
  Log.d("fanfan", "onStartCommand");
  return super.onStartCommand(intent, flags, startId);
 }

public void onDestroy() {
    //    
    player.stop();
    //    ,         ,        
    player.release();
    Log.d("fanfan", "onDestroy");
    super.onDestroy();
  }

첫 번 째 단 계 는 서비스 류 를 계승 할 종 류 를 찾 는 것 이다.

package fry;

import java.io.File;
import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

public class myService extends Service{

  //     
  private MediaPlayer player;
  /**
   *             
   */
  @Override
  public IBinder onBind(Intent arg0) {
    Log.d("fanfan", "onBind");
    return null;
  }
  /**
   * service      
   */
  @Override
  public void onCreate() {
    File file=new File(Environment.getExternalStorageDirectory(),"a.mp3");
    player =new MediaPlayer();
    try {
      //     
      player.setDataSource(file.getAbsolutePath());
    } catch (Exception e) {
      e.printStackTrace();
    } 
    Log.d("fanfan", "onCreate");
    super.onCreate();
  }
  
  /**
   * service start   
   */
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    
    try {
      //         ,       ,      onPrepared  
      player.setOnPreparedListener(new OnPreparedListener() {
        @Override
        //             
        public void onPrepared(MediaPlayer arg0) {
          //    
          player.start();
        }
      });
      
      //    ,      
      //    ,              
      player.prepareAsync();
      
    } catch (Exception e) {
      e.printStackTrace();
    } 
    
    Log.d("fanfan", "onStartCommand");
    return super.onStartCommand(intent, flags, startId);
  }
  
  /**
   * service      
   */
  @Override
  public void onDestroy() {
    //    
    player.stop();
    //    ,         ,        
    player.release();
    Log.d("fanfan", "onDestroy");
    super.onDestroy();
  }

}
두 번 째 단 계 는 이 설정 의 감청 서비스 도 설정 해 야 합 니 다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.playMusic"
  android:versionCode="1"
  android:versionName="1.0" >

  <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

  <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
      android:name="fry.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="fry.Activity01" android:exported="true"></activity>
    
    <service android:name="fry.myService">
      
    </service>
    
  </application>

</manifest>
세 번 째,음악 재생 또는 종료

package fry;

import com.example.playMusic.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class Activity01 extends Activity{
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity01);
  }
  
  public void onClick(View view){
    Intent intent=new Intent();
    intent.setClass(this, myService.class);
    switch(view.getId()){
    case R.id.btn_start://    ,    
      startService(intent);
      break;
    case R.id.btn_stop://    ,    
      stopService(intent);
      break;
    }
  }
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기