nirasan's tech blog

趣味や仕事の覚え書きです。Linux, Perl, PHP, Ruby, Javascript, Android, Cocos2d-x, Unity などに興味があります。

Unity で Android のネイティブプラグインの実装 - ローカル通知を送信する

はじめに

ネイティブプラグイン作成環境構築参考サイト

参考サイトにない作業

Unity プラグインの追加

  • 作業環境が Mac だったので "5.2.3 Unityプラグインの追加" で Unity.app 以下にある classes.jar を直接指定できなかった。
  • そのため、プロジェクト直下の .classpath ファイルを直接開き、以下を追記した。
    <classpathentry exported="true" kind="lib" path="/Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidPlayer/bin/classes.jar"/>

AndroidManifest.xml の追加

  • パーミッションを追加したかったので AndroidManifest.xml が必要になった。
  • Macの場合、デフォルトのファイルは以下にあるので、これをコピーして編集する。
    • /Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidPlayer

android-support-v4.jar の追加

  • プレグインのプロジェクトの libs から Unity の Plubins/Android 直下にファイルをコピーする。

ローカル通知の実装

  • 起動時にローカル通知を送信し、通知押下でアプリを起動するプラグインを作成した。

ネイティブプラグインの実装

  • 参考サイトのとおりに以下のコードを Eclipse で作成し、エクスポートして jar を Plugins/Android 以下に保存する
参考サイト

http://phardera.blogspot.jp/2013/12/unity-3d-local-notification-for-android.html
http://qiita.com/ksk_kbys/items/2d864f3cad2e104ddfe2
http://blog.haw.co.jp/android/?p=332

package info.nirasan.notifytest;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.unity3d.player.UnityPlayer;

public class NotifyTest {
	public void sendNotification() {
		
		Log.i("Unity", "START sendNotification()");
		
	    // Intent の作成
		Activity activity =UnityPlayer.currentActivity;
		Context context = activity.getApplicationContext();
		Class<?> cc = null;
        try {
        	cc = activity.getClassLoader().loadClass("com.unity3d.player.UnityPlayerNativeActivity");
        } catch (ClassNotFoundException e1) {
        	e1.printStackTrace();
        	return;
        }
        
	    int id =(int)(Math.random()*10000.0f)+1;
        Intent intent2 = new Intent(context, cc);
        intent2.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent2,
                PendingIntent.FLAG_UPDATE_CURRENT);
	     
	    // LargeIcon の Bitmap を生成
        final PackageManager pm=context.getPackageManager();
        ApplicationInfo applicationInfo = null;
        try {
          applicationInfo = pm.getApplicationInfo(context.getPackageName(),PackageManager.GET_META_DATA);
        } catch (NameNotFoundException e) {
          e.printStackTrace();
          return;
        }
        final int appIconResId=applicationInfo.icon;
	    Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), appIconResId);
	     
	    // NotificationBuilderを作成
	    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
	    builder.setContentIntent(contentIntent);
	    // ステータスバーに表示されるテキスト
	    builder.setTicker("Ticker");
	    // アイコン
	    builder.setSmallIcon(appIconResId);
	    // Notificationを開いたときに表示されるタイトル
	    builder.setContentTitle("ContentTitle");
	    // Notificationを開いたときに表示されるサブタイトル
	    builder.setContentText("ContentText");
	    // Notificationを開いたときに表示されるアイコン
	    builder.setLargeIcon(largeIcon);
	    // 通知するタイミング
	    builder.setWhen(System.currentTimeMillis());
	    // 通知時の音・バイブ・ライト
	    builder.setDefaults(Notification.DEFAULT_SOUND
	            | Notification.DEFAULT_VIBRATE
	            | Notification.DEFAULT_LIGHTS);
	    // タップするとキャンセル(消える)
	    builder.setAutoCancel(true);
	     
	    // NotificationManagerを取得
	    NotificationManager manager = (NotificationManager) activity.getSystemService(Service.NOTIFICATION_SERVICE);
	    // Notificationを作成して通知
	    manager.notify(id, builder.build());
	    
		Log.i("Unity", "END sendNotification()");

	}
}

パーミッションの追加

  • デフォルトの AndroidManifest.xml をコピーしてきて、以下の項目を 直下に追記する。
<uses-permission android:name="android.permission.VIBRATE"/>

Unity 側の実装

  • 以下のスクリプトを Plugins/NotifyTestScript.cs として作成し、任意の GameObject にアタッチする。
sing UnityEngine;
using System.Collections;

public class NotifyTestScript : MonoBehaviour {

	static AndroidJavaObject m_plugin = null;
	static GameObject        m_instance;

	public void Awake () {
		m_instance = gameObject;
#if UNITY_ANDROID && !UNITY_EDITOR
		// プラグイン名をパッケージ名+クラス名で指定する。
		m_plugin = new AndroidJavaObject( "info.nirasan.notifytest.NotifyTest" );
#endif
	}

	public void Start()
	{
		Debug.Log ("Start NotifyTestScript");
#if UNITY_ANDROID && !UNITY_EDITOR
		if (m_plugin != null){
			m_plugin.Call("sendNotification");
		}
#endif
	}
}