Unity3d 调用Android震动

Android 代码如下:

package com.xuefei.vibration;

import com.unity3d.player.UnityPlayerActivity;

import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;

public class MainActivity extends UnityPlayerActivity {

	static MainActivity ma;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ma = this;
	}

	/**
	 * final Activity activity :调用该方法的Activity实例 long milliseconds :震动的时长,单位是毫秒
	 * long[] pattern :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒
	 * boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次
	 */

	public static void Vibrate(final String milliseconds) {
		Vibrator vib = (Vibrator) ma.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(Long.parseLong(milliseconds));
	}

	/*public static void Vibrate(final long[] pattern, boolean isRepeat) {
		Vibrator vib = (Vibrator) ma.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(pattern, isRepeat ? 1 : -1);
	}*/
}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xuefei.vibration"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />
    
    <uses-permission android:name="android.permission.VIBRATE" />  

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.xuefei.vibration.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>
    </application>

</manifest>


unity3d 代码如下:

using UnityEngine;
using System.Collections;

public class VibrateTest : MonoBehaviour {

	AndroidJavaClass jc;
	AndroidJavaObject jo;
	// Use this for initialization
	void Start () {
		jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
		jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	void OnGUI()
	{
		if (GUI.Button (new Rect (0, 0, 200, 100), "Vibrate")) {
			jo.CallStatic("Vibrate","100");
		}
	}
}


文件操作流程:

安卓创建项目,我设置了目标版本4.0,Is Library ,

Unity 关键目录如下,文件从Android项目拷贝过来

Unity3d 调用Android震动_第1张图片


真机测试震动100毫秒

Unity3d 调用Android震动_第2张图片


点击这里下载工程文件

unity版本4.6.2f1



你可能感兴趣的:(eclipse,android,unity3d)