AIDL(Android Interface definition language)學習筆記一 – Android移動開發技術文章_手機開發 Android移動開發教學課程

一、源碼結構:

二、Manifest文件

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.qiao.aidl.test1" 
    android:versionCode="1" 
    android:versionName="1.0" > 
 
    <uses-sdk android:minSdkVersion="7" /> 
     
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
     
    <application 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" > 
        <activity 
            android:label="@string/app_name" 
            android:name=".AIDL_Demo_1Activity" > 
            <intent-filter > 
                <action android:name="android.intent.action.MAIN" /> 
 
                <category android:name="android.intent.category.LAUNCHER" /> 
            </intent-filter> 
        </activity> 
        <service android:name="com.qiao.aidl.service.MusicService" android:enabled="true"></service> 
    </application> 
 
</manifest> 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qiao.aidl.test1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />
 
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AIDL_Demo_1Activity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.qiao.aidl.service.MusicService" android:enabled="true"></service>
    </application>

</manifest>

 

三、AIDL文件

package com.qiao.aidl.aidl; 
 
interface IServicePlayer{ 
    void play(); 
    void pause(); 
    void stop(); 
    int getDuration(); 
    int getCurrentPosition(); 
    void seekTo(int current); 
    boolean setLoop(boolean loop); 

package com.qiao.aidl.aidl;

interface IServicePlayer{
 void play();
 void pause();
 void stop();
 int getDuration();
 int getCurrentPosition();
 void seekTo(int current);
 boolean setLoop(boolean loop);
}


四、MusicService

package com.qiao.aidl.service; 
 
import java.io.File; 
import java.io.IOException; 
 
import com.qiao.aidl.aidl.IServicePlayer; 
import com.qiao.aidl.test1.R; 
 
import android.app.Service; 
import android.content.Intent; 
import android.media.MediaPlayer; 
import android.os.Environment; 
import android.os.IBinder; 
import android.os.RemoteException; 
 
public class MusicService extends Service{ 
     
    public static final String TAG = "MusicService"; 
     
    public static MediaPlayer mediaPlayer = null; 
     
    public boolean isPause = false; 
     
     
    @Override 
    public void onCreate() { 
        // TODO Auto-generated method stub  
        super.onCreate(); 
        //第一種加載音樂文件的方法,即把音樂文件放在res資源文件中  
//      mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.test);  
        //第二種加載音樂文件的方法,讀取本地SD卡上的音樂文件  
        mediaPlayer = new MediaPlayer(); 
        try { 
            loadMusicFileFromSDCard("光輝歲月_Beyond.mp3"); 
        } catch (IOException e) { 
            System.out.println("文件讀取失敗"); 
            e.printStackTrace(); 
        } 
    } 
     
    private void loadMusicFileFromSDCard(String fileName) throws IOException{ 
        File audioFile = new File("/sdcard/DUOMI/music/",fileName);   
        mediaPlayer.reset();   
        mediaPlayer.setDataSource(audioFile.getAbsolutePath());   
        mediaPlayer.prepare();   
    } 
 
    IServicePlayer.Stub stub = new IServicePlayer.Stub() { 
         
        @Override 
        public void stop() throws RemoteException { 
            // TODO Auto-generated method stub  
            mediaPlayer.start(); 
        } 
         
        @Override 
        public boolean setLoop(boolean loop) throws RemoteException { 
            // TODO Auto-generated method stub  
            return false; 
        } 
         
        @Override 
        public void seekTo(int current) throws RemoteException { 
            // TODO Auto-generated method stub  
            mediaPlayer.seekTo(current); 
        } 
         
        @Override 
        public void play() throws RemoteException { 
            // TODO Auto-generated method stub  
            mediaPlayer.start(); 
        } 
         
        @Override 
        public void pause() throws RemoteException { 
            // TODO Auto-generated method stub  
            mediaPlayer.pause(); 
        } 
         
        @Override 
        public int getDuration() throws RemoteException { 
            // TODO Auto-generated method stub  
            return mediaPlayer.getDuration(); 
        } 
         
        @Override 
        public int getCurrentPosition() throws RemoteException { 
            // TODO Auto-generated method stub  
            return mediaPlayer.getCurrentPosition(); 
        } 
    }; 
 
    @Override 
    public IBinder onBind(Intent intent) { 
        return stub; 
    } 

package com.qiao.aidl.service;

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

import com.qiao.aidl.aidl.IServicePlayer;
import com.qiao.aidl.test1.R;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;

public class MusicService extends Service{
 
 public static final String TAG = "MusicService";
 
 public static MediaPlayer mediaPlayer = null;
 
 public boolean isPause = false;
 
 
 @Override
 public void onCreate() {
  // TODO Auto-generated method stub
  super.onCreate();
  //第一種加載音樂文件的方法,即把音樂文件放在res資源文件中
//  mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.test);
  //第二種加載音樂文件的方法,讀取本地SD卡上的音樂文件
  mediaPlayer = new MediaPlayer();
  try {
   loadMusicFileFromSDCard("光輝歲月_Beyond.mp3");
  } catch (IOException e) {
   System.out.println("文件讀取失敗");
   e.printStackTrace();
  }
 }
 
 private void loadMusicFileFromSDCard(String fileName) throws IOException{
  File audioFile = new File("/sdcard/DUOMI/music/",fileName); 
        mediaPlayer.reset(); 
        mediaPlayer.setDataSource(audioFile.getAbsolutePath()); 
        mediaPlayer.prepare(); 
 }

 IServicePlayer.Stub stub = new IServicePlayer.Stub() {
  
  @Override
  public void stop() throws RemoteException {
   // TODO Auto-generated method stub
   mediaPlayer.start();
  }
  
  @Override
  public boolean setLoop(boolean loop) throws RemoteException {
   // TODO Auto-generated method stub
   return false;
  }
  
  @Override
  public void seekTo(int current) throws RemoteException {
   // TODO Auto-generated method stub
   mediaPlayer.seekTo(current);
  }
  
  @Override
  public void play() throws RemoteException {
   // TODO Auto-generated method stub
   mediaPlayer.start();
  }
  
  @Override
  public void pause() throws RemoteException {
   // TODO Auto-generated method stub
   mediaPlayer.pause();
  }
  
  @Override
  public int getDuration() throws RemoteException {
   // TODO Auto-generated method stub
   return mediaPlayer.getDuration();
  }
  
  @Override
  public int getCurrentPosition() throws RemoteException {
   // TODO Auto-generated method stub
   return mediaPlayer.getCurrentPosition();
  }
 };

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

 

五、Activity

package com.qiao.aidl.test1; 
 
import com.qiao.aidl.aidl.IServicePlayer; 
import com.qiao.aidl.service.MusicService; 
 
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.Handler; 
import android.os.IBinder; 
import android.os.Message; 
import android.view.View; 
import android.widget.Button; 
import android.widget.SeekBar; 
import android.widget.SeekBar.OnSeekBarChangeListener; 
 
public class AIDL_Demo_1Activity extends Activity { 
     
    private static final String TAG = "AIDL_Demo_1Activity"; 
     
    private SeekBar seekBar = null; 
    private Button btnPlay = null; 
     
    IServicePlayer iServicePlayer = null; 
    boolean isPlay = false; 
    boolean isLoop = false; 
     
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        seekBar = (SeekBar)findViewById(R.id.seekBar); 
        btnPlay = (Button)findViewById(R.id.btnPlay); 
         
        bindService(new Intent(AIDL_Demo_1Activity.this, MusicService.class), conn, Context.BIND_AUTO_CREATE); 
        startService(new Intent(AIDL_Demo_1Activity.this, MusicService.class)); 
         
        btnPlay.setOnClickListener(new View.OnClickListener() { 
             
            @Override 
            public void onClick(View v) { 
                System.out.println(TAG + " play button onClicked."); 
                 
                if(!isPlay){ 
                    try { 
                        iServicePlayer.play(); 
                    } catch (Exception e) { 
                        e.printStackTrace();     
                    } 
                    btnPlay.setText("暫停"); 
                    isPlay = true; 
                } else { 
                    try { 
                        iServicePlayer.pause(); 
                    } catch (Exception e) { 
                        e.printStackTrace(); 
                    } 
                    btnPlay.setText("播放"); 
                    isPlay = false; 
                } 
            } 
        }); 
         
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { 
             
            @Override 
            public void onStopTrackingTouch(SeekBar seekBar) { 
                if(iServicePlayer != null){ 
                    try { 
                        iServicePlayer.seekTo(seekBar.getProgress()); 
                    } catch (Exception e) { 
                        e.printStackTrace(); 
                    } 
                } 
            } 
             
            @Override 
            public void onStartTrackingTouch(SeekBar seekBar) { 
                 
            } 
             
            @Override 
            public void onProgressChanged(SeekBar seekBar, int progress, 
                    boolean fromUser) { 
                 
            } 
        }); 
        handler.post(updateThread); 
    } 
     
    private ServiceConnection conn = new ServiceConnection(){ 
 
        @Override 
        public void onServiceConnected(ComponentName name, IBinder service) { 
            System.out.println(TAG + " : onServiceConnected()"); 
            iServicePlayer = IServicePlayer.Stub.asInterface(service); 
        } 
 
        @Override 
        public void onServiceDisconnected(ComponentName name) { 
            System.out.println(TAG + " : onServiceDisconnected()"); 
        } 
         
    }; 
     
    Handler handler = new Handler(){ 
 
        @Override 
        public void handleMessage(Message msg) { 
            super.handleMessage(msg); 
        } 
         
    }; 
     
    private Runnable updateThread = new Runnable() { 
         
        @Override 
        public void run() { 
            if(iServicePlayer != null){ 
                try { 
                    seekBar.setMax(iServicePlayer.getDuration()); 
                    seekBar.setProgress(iServicePlayer.getCurrentPosition()); 
                } catch (Exception e) { 
                    e.printStackTrace(); 
                } 
            } 
            handler.post(updateThread); 
        } 
    }; 

package com.qiao.aidl.test1;

import com.qiao.aidl.aidl.IServicePlayer;
import com.qiao.aidl.service.MusicService;

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.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class AIDL_Demo_1Activity extends Activity {
 
 private static final String TAG = "AIDL_Demo_1Activity";
 
 private SeekBar seekBar = null;
 private Button btnPlay = null;
 
 IServicePlayer iServicePlayer = null;
 boolean isPlay = false;
 boolean isLoop = false;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        seekBar = (SeekBar)findViewById(R.id.seekBar);
        btnPlay = (Button)findViewById(R.id.btnPlay);
       
        bindService(new Intent(AIDL_Demo_1Activity.this, MusicService.class), conn, Context.BIND_AUTO_CREATE);
        startService(new Intent(AIDL_Demo_1Activity.this, MusicService.class));
       
        btnPlay.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    System.out.println(TAG + " play button onClicked.");
    
    if(!isPlay){
     try {
      iServicePlayer.play();
     } catch (Exception e) {
      e.printStackTrace(); 
     }
     btnPlay.setText("暫停");
     isPlay = true;
    } else {
     try {
      iServicePlayer.pause();
     } catch (Exception e) {
      e.printStackTrace();
     }
     btnPlay.setText("播放");
     isPlay = false;
    }
   }
  });
       
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   
   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    if(iServicePlayer != null){
     try {
      iServicePlayer.seekTo(seekBar.getProgress());
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   }
   
   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    
   }
   
   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    
   }
  });
        handler.post(updateThread);
    }
   
    private ServiceConnection conn = new ServiceConnection(){

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   System.out.println(TAG + " : onServiceConnected()");
   iServicePlayer = IServicePlayer.Stub.asInterface(service);
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   System.out.println(TAG + " : onServiceDisconnected()");
  }
     
    };
   
    Handler handler = new Handler(){

  @Override
  public void handleMessage(Message msg) {
   super.handleMessage(msg);
  }
     
    };
   
    private Runnable updateThread = new Runnable() {
  
  @Override
  public void run() {
   if(iServicePlayer != null){
    try {
     seekBar.setMax(iServicePlayer.getDuration());
     seekBar.setProgress(iServicePlayer.getCurrentPosition());
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
   handler.post(updateThread);
  }
 };
}

 摘自 qiaoning13256的專欄

發佈留言