Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

在 Android Studio 中實作 Service AIDL 遠端通訊(附完整程式碼)

今天開發時需要用到 AIDL 呼叫。過去用 Eclipse 時教學多、上手快,剛換到 Android Studio 後,雖然得承認它確實強大,但很多功能還要自己摸索——AIDL 就是其中之一。

AIDL(Android Interface Definition Language)是 Android 的介面定義語言,可讓某個 Service 與多個應用程式元件進行跨行程通訊,進而實現多個應用共用同一個 Service。

以下用一個小 demo 展示 AIDL 在 Android Studio 中的完整流程。

步驟一:建立 Service 骨架

先搭一個最簡單的 Service 框架,只包含 startService(intent),程式碼見後文。

步驟二:新增 AIDL 檔

透過 IDE 新建 AIDL 檔案。

建立完成後,AIDL 檔就出現在專案中了。

步驟三:讓 AIDL 產生對應的 Java 檔

此時你會發現並沒有相對應的 Java 檔產生。其實 Android Studio 是具備自動產生能力的,只是需要某些資訊齊備才會觸發。此時到 build --> generated --> source --> aidl --> test --> debug 底下看,目錄裡空空如也。

步驟四:對齊 package 名稱(關鍵一步)

打開 AndroidManifest.xml,確認 package 的值。

接著確認 AIDL 檔所在的套件名與 AndroidManifest.xml 的 package 是否一致。一致的话,點「Build」→「Make Project」就會產生對應的 Java 檔;不一致就先把 AIDL 的套件名改成一致,再產生一次。

完成後,就能在程式裡透過 AIDL 呼叫遠端 Service 的方法了。

MainActivity.java

public class MainActivity extends ActionBarActivity {

  private MyServiceAIDL myServiceAIDL;
  private Intent binderIntent;
  private final static boolean create_flag=true;
  private final static boolean destory_flag=false;
  private final static String TAG="MainActivity";

  private ServiceConnection sc = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
      myServiceAIDL = MyServiceAIDL.Stub.asInterface(service);
      try {
        //通過AIDL遠程調用
        Log.d(TAG,"++start download++");
        myServiceAIDL.DownLoad();
      } catch (RemoteException e) {
        e.printStackTrace();
      }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG,"++MainActivity onCreate++");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //開啟服務
    Intent intent = new Intent(this, MainService.class);
    startService(intent);

    //連接遠程Service和Activity
    binderIntent = new Intent(this, MainService.class);
    Bundle bundle = new Bundle();
    bundle.putBoolean("flag",create_flag);
    binderIntent.putExtras(bundle);
    bindService(binderIntent, sc, BIND_AUTO_CREATE);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG,"++MainActivity onDestroy++");

    //暫停服務
    Intent intent = new Intent(this, MainService.class);
    stopService(intent);

    //斷開與遠程Service的連接
    unbindService(sc);
  }
}

MainService.java

public class MainService extends Service {

  boolean flag;
  private final static String TAG = "MainService";

  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "++MainService onDestroy++");
    flag = false;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
  }

  @Override
  public void onCreate() {
    super.onCreate();
    Log.d(TAG, "++MainService onCreate++");

    Notification no = new Notification(R.drawable.ic_launcher, "有通知到來", System.currentTimeMillis());
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
    no.setLatestEventInfo(this, "AIDLDemo", "running", pi);
    startForeground(1, no);
  }

  @Override
  public IBinder onBind(Intent intent) {
    Bundle bundle = intent.getExtras();
    flag = bundle.getBoolean("flag");
    System.out.println(flag);
    return ms;
  }

  MyServiceAIDL.Stub ms = new MyServiceAIDL.Stub() {
    @Override
    public void DownLoad() throws RemoteException {
      new Thread(new Runnable() {
        int i = 0;

        @Override
        public void run() {
          //未達到線程條件,會一直在後台運行,就算服務已經關閉
          while (flag) {
            try {
              i++;
              System.out.println("i的值是" + i);
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          System.out.println("退出服務");
        }
      }).start();
    }
  };
}

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@drawable/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>

    <service
        android:name=".MainService"
        android:process=":remote"></service>
</application>

MyServiceAIDL.aidl

// myServiceAIDL.aidl
package com.example.wanghao.aidldemo;

// Declare any non-default types here with import statements

interface MyServiceAIDL {
  void DownLoad();
}

Ubuntu 12.04(64位)安裝Android Studio 全過程 https://www.linuxidc.com/Linux/2013-05/84812.htm

Android Studio v0.1嘗鮮 https://www.linuxidc.com/Linux/2013-05/84681.htm

Android Studio使用教程 https://www.linuxidc.com/Linux/2013-05/84579.htm

Android Studio開發指南 https://www.linuxidc.com/Linux/2013-05/84543.htm

Android Studio設置主題 和 不支持中文的問題解決方法 https://www.linuxidc.com/Linux/2013-05/84488.htm

Android Studio 下載安裝以及不能打開的解決辦法 https://www.linuxidc.com/Linux/2013-05/84409.htm

Android Studio安裝使用圖文教程 https://www.linuxidc.com/Linux/2014-09/106914.htm

Copyright © Linux教程網 All Rights Reserved