Native+WebApp中Phonegap调用Android Activity

摘自:http://topmanopensource.iteye.com/blog/1577717

 

          在项目采用Native+Web方式开发,Android团队开发一个模块的代码,WebApp phonegap开发几个模块,需要将Android中的模块潜入到Phonegap开发的几个模块中。需要通过Phonegap调用Android 的Activity。

demo如下:

 

Phonegap插件类:

Java代码 
  1. package com.easyway.etrip.plugins; 
  2.  
  3. import org.json.JSONArray; 
  4.  
  5. import android.app.Activity; 
  6. import android.content.Intent; 
  7. import android.os.Handler; 
  8. import android.os.Message; 
  9. import android.util.Log; 
  10.  
  11. import com.phonegap.api.Plugin; 
  12. import com.phonegap.api.PluginResult; 
  13. /**
  14. * Phonegap 调用Android Activity的插件
  15. *
  16. * @Title:
  17. * @Description: 实现TODO
  18. * @Copyright:Copyright (c) 2011
  19. * @Company:易程科技股份有限公司
  20. * @Date:2012-7-5
  21. * @author  longgangbai
  22. * @version 1.0
  23. */ 
  24. publicclass AndroidActivityPlugin  extends Plugin{ 
  25.       
  26.     private Object synObj = new Object(); 
  27.     @Override 
  28.     public PluginResult execute(String action, JSONArray data, String callbackID) { 
  29.         // TODO Auto-generated method stub 
  30.         if(action.equals("startActivity")){ 
  31.             PluginResult result = null
  32.              
  33.             try {        
  34.                 PluginResult.Status status = PluginResult.Status.OK; 
  35.                 if(action.equals("startActivity")){  
  36.                     Log.e("test", "test plugin js -> java~~~~"+data.getString(0));  
  37.                     Log.e("test", "test plugin js -> java~~~~");                  
  38.                     result = new PluginResult(status, data.getString(0));    
  39.                     Message msg=new Message(); 
  40.                     msg.what=1
  41.                     Log.e("参数信息:", data.toString()); 
  42.                     msg.obj=data.getString(0); 
  43.                     handler.sendMessage(msg); 
  44.                     sleep(); 
  45.                 } 
  46.             } catch (Exception e) { 
  47.             } 
  48.             return result; 
  49.         }else
  50.             returnnew PluginResult(PluginResult.Status.INVALID_ACTION); 
  51.         } 
  52.      
  53.     } 
  54.     private Handler handler = new Handler() { 
  55.         publicvoid handleMessage(Message msg) { 
  56.             if (msg == null) { 
  57.                 return
  58.             } 
  59.             switch (msg.what) { 
  60.             case1
  61.                 String className=msg.obj.toString(); 
  62.                 try
  63.                     Class activityClass = Class.forName(className); 
  64.                     Intent intent = new Intent(ctx.getBaseContext(), activityClass);//你想去的activity(exp:Temp) 
  65.                     ctx.startActivityForResult(AndroidActivityPlugin.this, intent, 1); 
  66.                 } catch (ClassNotFoundException e) { 
  67.                     Log.e("Why", "错误原因:"+className); 
  68.                     e.printStackTrace(); 
  69.                 } 
  70.                 break
  71.             } 
  72.         }; 
  73.     }; 
  74.      
  75.     @Override 
  76.     publicvoid onActivityResult(int requestCode, int resultCode, Intent intent) { 
  77.         // TODO Auto-generated method stub   
  78.         if(requestCode==1){ 
  79.             if(resultCode == Activity.RESULT_CANCELED){ 
  80.                 //返回时调用 
  81.                 Log.e("test", "result plugin -> java~~~~");  
  82.                 Log.e("test", "result plugin -> java~~~~");  
  83.                 weakup(); 
  84.             } 
  85.         }else
  86.             super.onActivityResult(requestCode, resultCode, intent); 
  87.         } 
  88.     } 
  89.      
  90.      
  91.     privatevoid sleep() 
  92.     { 
  93.         try 
  94.         { 
  95.             synchronized(synObj) 
  96.             { 
  97.                 synObj.wait(); 
  98.             } 
  99.         } 
  100.         catch (InterruptedException e) 
  101.         { 
  102.             e.printStackTrace(); 
  103.         } 
  104.     } 
  105.      
  106.     privatevoid weakup() 
  107.     { 
  108.         synchronized(synObj) 
  109.         { 
  110.             synObj.notify(); 
  111.         } 
  112.     } 
  113.      
package com.easyway.etrip.plugins;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
/**
 * Phonegap 调用Android Activity的插件
 * 
 * @Title: 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-7-5
 * @author  longgangbai
 * @version 1.0
 */
public class AndroidActivityPlugin  extends Plugin{
	 
	private Object synObj = new Object();
	@Override
	public PluginResult execute(String action, JSONArray data, String callbackID) {
		// TODO Auto-generated method stub
		if(action.equals("startActivity")){
			PluginResult result = null;
			
			try {		
				PluginResult.Status status = PluginResult.Status.OK;
				if(action.equals("startActivity")){ 
					Log.e("test", "test plugin js -> java~~~~"+data.getString(0)); 
					Log.e("test", "test plugin js -> java~~~~"); 				
					result = new PluginResult(status, data.getString(0));	
					Message msg=new Message();
					msg.what=1;
					Log.e("参数信息:", data.toString());
					msg.obj=data.getString(0);
					handler.sendMessage(msg);
					sleep();
				}
			} catch (Exception e) {
			}
			return result;
		}else {
            return new PluginResult(PluginResult.Status.INVALID_ACTION);
		}
	
	}
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg == null) {
				return;
			}
			switch (msg.what) {
			case 1:
				String className=msg.obj.toString();
				try {
					Class activityClass = Class.forName(className);
					Intent intent = new Intent(ctx.getBaseContext(), activityClass);//你想去的activity(exp:Temp)
					ctx.startActivityForResult(AndroidActivityPlugin.this, intent, 1);
				} catch (ClassNotFoundException e) {
					Log.e("Why", "错误原因:"+className);
					e.printStackTrace();
				}
				break;
			}
		};
	};
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub	
		if(requestCode==1){
			if(resultCode == Activity.RESULT_CANCELED){
				//返回时调用
				Log.e("test", "result plugin -> java~~~~"); 
				Log.e("test", "result plugin -> java~~~~"); 
				weakup();
			}
		}else{
			super.onActivityResult(requestCode, resultCode, intent);
		}
	}
	
	
	private void sleep()
    {
        try
        {
            synchronized(synObj)
            {
                synObj.wait();
            }
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
	
	private void weakup()
    {
        synchronized(synObj)
        {
            synObj.notify();
        }
    }
	
}




 

 

 

phonegap启动类:

Java代码 
  1. package com.easyway.etrip; 
  2.  
  3. import android.os.Bundle; 
  4.  
  5. import com.phonegap.DroidGap; 
  6. /**
  7. * phonegap启动类
  8. *
  9. * @Title:
  10. * @Description: 实现TODO
  11. * @Copyright:Copyright (c) 2011
  12. * @Company:易程科技股份有限公司
  13. * @Date:2012-7-5
  14. * @author  longgangbai
  15. * @version 1.0
  16. */ 
  17. publicclass PhonegapAndroidActivityActivity extends DroidGap  { 
  18.     /** Called when the activity is first created. */ 
  19.     @Override 
  20.     publicvoid onCreate(Bundle savedInstanceState) { 
  21.           super.onCreate(savedInstanceState); 
  22.           super.loadUrl("file:///android_asset/www/index.html"); 
  23.     } 
package com.easyway.etrip;

import android.os.Bundle;

import com.phonegap.DroidGap;
/**
 * phonegap启动类
 * 
 * @Title: 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-7-5
 * @author  longgangbai
 * @version 1.0
 */
public class PhonegapAndroidActivityActivity extends DroidGap  {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	  super.onCreate(savedInstanceState);
          super.loadUrl("file:///android_asset/www/index.html");
    }
}

 

Android的Activity类:

Java代码 
  1. package com.easyway.etrip; 
  2.  
  3. import android.app.Activity; 
  4. import android.os.Bundle; 
  5. /**
  6. *
  7. *
  8. * @Title:
  9. * @Description: 实现TODO
  10. * @Copyright:Copyright (c) 2011
  11. * @Company:易程科技股份有限公司
  12. * @Date:2012-7-5
  13. * @author  longgangbai
  14. * @version 1.0
  15. */ 
  16. publicclass ThirdAndroidActivity extends Activity { 
  17.     /** Called when the activity is first created. */ 
  18.     @Override 
  19.     publicvoid onCreate(Bundle savedInstanceState) { 
  20.         super.onCreate(savedInstanceState); 
  21.         super.setContentView(R.layout.main); 
  22.     } 
package com.easyway.etrip;

import android.app.Activity;
import android.os.Bundle;
/**
 * 
 * 
 * @Title: 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-7-5
 * @author  longgangbai
 * @version 1.0
 */
public class ThirdAndroidActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);
    }
}

 

 

 

phonegap的插件配置类phonegap.xml:

Xml代码 
  1. <pluginname="AndroidActivity"value="com.easyway.etrip.plugins.AndroidActivityPlugin"/> 
   <plugin name="AndroidActivity" value="com.easyway.etrip.plugins.AndroidActivityPlugin"/>

 

androidActivity.js

Js代码 
  1. var AndroidActivity=function(){};  
  2. AndroidActivity.prototype.startActivity = function(success, fail,parmas) 
  3. {  
  4.     return PhoneGap.exec(  
  5.             function(args){ success(args); },  
  6.             function(args){ fail(args); },  
  7.             'AndroidActivity', //java类  
  8.             'startActivity', //action  
  9.             [parmas] //params  
  10.              );  
  11. }; 
  12. PhoneGap.addConstructor(function() { 
  13.     PhoneGap.addPlugin('androidActivity', new AndroidActivity()); 
  14. }); 
var AndroidActivity=function(){}; 
AndroidActivity.prototype.startActivity = function(success, fail,parmas)
{ 
    return PhoneGap.exec( 
            function(args){ success(args); }, 
            function(args){ fail(args); }, 
            'AndroidActivity', //java类 
            'startActivity', //action 
            [parmas] //params 
             ); 
};
PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin('androidActivity', new AndroidActivity());
});

 

 

调用的测试类:

 

Html代码 
  1. <!DOCTYPE HTML> 
  2. <html> 
  3.   <head> 
  4.     <metaname="viewport"content="width=320; user-scalable=no"/> 
  5.     <metahttp-equiv="Content-type"content="text/html; charset=utf-8"> 
  6.     <title>Minimal AppLaud App</title> 
  7.  
  8.       <scripttype="text/javascript"charset="utf-8"src="phonegap-1.4.1.js"></script> 
  9.       <scripttype="text/javascript"charset="utf-8"src="androidActivity.js"></script> 
  10.       <scripttype="text/javascript"charset="utf-8"> 
  11.     function openAndroidActivity(){   
  12.         window.plugins.androidActivity.startActivity( 
  13.                 function(r){//alert(r); 
  14.                     }, 
  15.                 function(e){//alert(e); 
  16.                 }, 
  17.                 "com.easyway.etrip.ThirdAndroidActivity" 
  18.             ); 
  19.     } 
  20. </script> 
  21. </head> 
  22. <body> 
  23. <h1>Hello World</h1> 
  24.      <inputtype="button"value="打开Android Activity"onclick="javascript:openAndroidActivity();"> 
  25. </body> 
  26. </html> 
posted @ 2012-12-09 21:58  爱的angell  阅读(372)  评论(0编辑  收藏  举报