Unity調(diào)用安卓Native(Android Studio)

最后有項目下載地址
引入Unity的class.jar
Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\Classes.jar

導(dǎo)出.jar包

在AS中進行操作
PopupManager.java

package com.xxx.xxx;//Unity中的Bundle Idendtifier
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import com.unity3d.player.UnityPlayer;
public class PopupManager
{
  public static void ShowMessagePopup(String title, String message, String okButtonText) {
    AlertDialog.Builder messagePopup = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme()));
    messagePopup.setTitle(title);
    messagePopup.setMessage(message);
    messagePopup.setPositiveButton(okButtonText, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
              UnityPlayer.UnitySendMessage("AndroidMessagePopup", "OnMessagePopUpCallBack", "0");
  }
  });
  messagePopup.setOnKeyListener(KeyListener);
    messagePopup.setCancelable(false);
    messagePopup.show();
  }

  public static void ShowDialogPopup(String title, String message, String yesButtonText, String noButtonText) {
    AlertDialog.Builder dialogPopupBuilder = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme()));
    dialogPopupBuilder.setTitle(title);
    dialogPopupBuilder.setMessage(message);
    dialogPopupBuilder.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
              UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "0");
  }
  });
  dialogPopupBuilder.setNegativeButton(noButtonText, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
          UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "1");
  }
});
dialogPopupBuilder.setOnKeyListener(KeyListener);
dialogPopupBuilder.setCancelable(false);
dialogPopupBuilder.show();
}

public static void ShowRatePopup(String title, String message, String yesButtonText, String laterButtonText, String noButtonText) {
        AlertDialog.Builder ratePopupBuilder = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme()));
ratePopupBuilder.setTitle(title);
ratePopupBuilder.setMessage(message);
ratePopupBuilder.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UnityPlayer.UnitySendMessage("AndroidRateUsPopUp", "OnRatePopUpCallBack", "0");
}
});
ratePopupBuilder.setNegativeButton(noButtonText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UnityPlayer.UnitySendMessage("AndroidRateUsPopUp", "OnRatePopUpCallBack", "2");
}
});
ratePopupBuilder.setNeutralButton(laterButtonText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UnityPlayer.UnitySendMessage("AndroidRateUsPopUp", "OnRatePopUpCallBack", "1");
}
});
ratePopupBuilder.setOnKeyListener(KeyListener);
ratePopupBuilder.setCancelable(false);
ratePopupBuilder.show();
}
    @SuppressLint("InlinedApi")
private static int GetTheme(){
  int theme = 0;
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    theme = android.R.style.Theme_Material_Light_Dialog;
  } else {
    theme = android.R.style.Theme_Holo_Dialog;
  }
  return theme;
}
public static void OpenAppRatingPage(String url) {
        Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
UnityPlayer.currentActivity.startActivity(intent);
}
public static void OpenWebPage(String webUrl){
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
UnityPlayer.currentActivity.startActivity(browserIntent);
}
private static DialogInterface.OnKeyListener KeyListener = new OnKeyListener() {
    @Override
  public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
        Log.d("AndroidNative", "AndroidPopUp");
        UnityPlayer.UnitySendMessage("AndroidMessagePopup", "OnMessagePopUpCallBack", "0");
        UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "1");
        UnityPlayer.UnitySendMessage("AndroidRateUsPopUp", "OnRatePopUpCallBack", "2");
        dialog.dismiss();
      }
  return false;
}
};
}
//簡化版的
package cn.gfplay.LingFeiBaoDingMahjong;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import com.unity3d.player.UnityPlayer;
public class PopupManager
{
    public static void ShowDialogPopup(String title, String message, String yesButtonText, String noButtonText) {
        AlertDialog.Builder dialogPopupBuilder = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme()));
        dialogPopupBuilder.setTitle(title);
        dialogPopupBuilder.setMessage(message);
        dialogPopupBuilder.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "0");
            }
        });
        dialogPopupBuilder.setNegativeButton(noButtonText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "1");
            }
        });
        dialogPopupBuilder.setOnKeyListener(KeyListener);
        dialogPopupBuilder.setCancelable(false);
        dialogPopupBuilder.show();
    }
    @SuppressLint("InlinedApi")
    private static int GetTheme(){
        int theme = 0;
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            theme = android.R.style.Theme_Material_Light_Dialog;
        } else {
            theme = android.R.style.Theme_Holo_Dialog;
        }*/
        theme=android.R.style.Theme_Black;
        return theme;
    }
    public static void OpenWebPage(String webUrl){
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
        UnityPlayer.currentActivity.startActivity(browserIntent);
    }
    private static DialogInterface.OnKeyListener KeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                Log.d("AndroidNative", "AndroidPopUp");
                //UnityPlayer.UnitySendMessage("AndroidMessagePopup", "OnMessagePopUpCallBack", "0");
                UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "1");
                //UnityPlayer.UnitySendMessage("AndroidRateUsPopUp", "OnRatePopUpCallBack", "2");
                dialog.dismiss();
            }
            return false;
        }
    };
}

build.gradle修改

apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:26.+'
    testCompile 'junit:junit:4.12'
    compile files('libs/classes.jar')
}
//task to delete the old jar
task deleteOldJar(type: Delete) {    delete 'build/outputs/NativeExit.jar'}
//task to export contents as jar
task exportJar(type: Copy) {
    from('build/intermediates/bundles/debug/')
    into('build/outputs/')
    include('classes.jar')
    ///Rename the jar
    rename('classes.jar', 'NativeExit.jar')
}
exportJar.dependsOn(deleteOldJar, build)

02.將AS中的.jar引入unity中

string CLASS_NAME = "com.xxx.xxx.PopupManager";
AndroidJavaObject bridge = new AndroidJavaObject(CLASS_NAME);
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject act = jc.GetStatic<AndroidJavaObject>("currentActivity");
act.Call("runOnUiThread", new AndroidJavaRunnable(() =>
{
    bridge.CallStatic(methodName, args);
}));

這是unity與Android交互的部分篓吁,把Android中的方法注冊過來茫因,在Unity中調(diào)用

項目目錄截圖

image.png

AndroidStudio項目地址

https://github.com/574096324/Unity_AndroidStudio_Test.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市杖剪,隨后出現(xiàn)的幾起案子冻押,更是在濱河造成了極大的恐慌,老刑警劉巖盛嘿,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件洛巢,死亡現(xiàn)場離奇詭異,居然都是意外死亡孩擂,警方通過查閱死者的電腦和手機狼渊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來类垦,“玉大人狈邑,你說我怎么就攤上這事≡槿希” “怎么了米苹?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長砰琢。 經(jīng)常有香客問我蘸嘶,道長,這世上最難降的妖魔是什么陪汽? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任训唱,我火速辦了婚禮,結(jié)果婚禮上挚冤,老公的妹妹穿的比我還像新娘况增。我一直安慰自己,他們只是感情好训挡,可當(dāng)我...
    茶點故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布澳骤。 她就那樣靜靜地躺著,像睡著了一般澜薄。 火紅的嫁衣襯著肌膚如雪为肮。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天肤京,我揣著相機與錄音颊艳,去河邊找鬼。 笑死忘分,一個胖子當(dāng)著我的面吹牛棋枕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播饭庞,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼戒悠,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了舟山?” 一聲冷哼從身側(cè)響起萄凤,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎芬骄,沒想到半個月后蟆淀,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡若债,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年符相,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,809評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡啊终,死狀恐怖镜豹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蓝牲,我是刑警寧澤趟脂,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布,位于F島的核電站例衍,受9級特大地震影響昔期,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜佛玄,卻給世界環(huán)境...
    茶點故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一硼一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧梦抢,春花似錦般贼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至圈驼,卻和暖如春人芽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背绩脆。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工萤厅, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人靴迫。 一個月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓惕味,卻偏偏與公主長得像,于是被迫代替她去往敵國和親玉锌。 傳聞我的和親對象是個殘疾皇子名挥,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,724評論 2 351

推薦閱讀更多精彩內(nèi)容