loading...
Mostrando entradas con la etiqueta Android Codigo. Mostrar todas las entradas
Mostrando entradas con la etiqueta Android Codigo. Mostrar todas las entradas

martes, 29 de noviembre de 2011

Un ejemplo simple de OpenGL de Android con CLE

Medio de una extensión del lenguaje común (CLE) como middleware de interfaz, no tiene que preocuparse por JNI. La programación puede ser simple. En este ejemplo se copia de ejemplo NDK hola-GL2 con un pequeño cambio en el uso cle.

El código de C es el siguiente:

 

++ #include "vsopenapi.h"
…
-- bool setupGraphics(int w, int h) {
++ bool setupGraphics(void *object,int w, int h) {
…
}

-- void renderFrame() {
++ void renderFrame(void *object) {
…
}

-- extern "C" {
-- JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_init
(JNIEnv * env, jobject obj, jint width, jint height);
-- JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_step
(JNIEnv * env, jobject obj);
--};

-- JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_init
(JNIEnv * env, jobject obj, jint width, jint height)
-- {
-- setupGraphics(width, height);
-- }

-- JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_step(JNIEnv * env, jobject obj)
-- {
-- renderFrame();
-- }

++ VS_BOOL StarCoreService_Init(class ClassOfStarCore *starcore)
++ {
++ void *AtomicClass,*step_AtomicFunction,*init_AtomicFunction;
++ class ClassOfBasicSRPInterface *BasicSRPInterface;
++ class ClassOfSRPInterface *SRPInterface;
++
++ //--init star core
++ BasicSRPInterface = starcore ->GetBasicInterface();
++ SRPInterface = BasicSRPInterface ->GetSRPInterface
(BasicSRPInterface->QueryActiveService(NULL),"","");
++
++ //---Create Atomic Class, for define function, no attribute
++ AtomicClass = SRPInterface ->CreateAtomicObjectSimple
("TestItem","GLTestClass",NULL,NULL,NULL);
++ step_AtomicFunction = SRPInterface ->CreateAtomicFunctionSimple
(AtomicClass,"step","void step();",NULL,NULL,VS_FALSE,VS_FALSE);
++ init_AtomicFunction = SRPInterface ->CreateAtomicFunctionSimple
(AtomicClass,"init","VS_BOOL init(VS_INT32 width,VS_INT32 height);",
NULL,NULL,VS_FALSE,VS_FALSE);
++ //---Set Function Address
++ SRPInterface -> SetAtomicFunction(init_AtomicFunction,(void *)setupGraphics);
++ SRPInterface -> SetAtomicFunction(step_AtomicFunction,(void *)renderFrame);
++ SRPInterface -> Release();
++ return VS_TRUE;
++ }

++ void StarCoreService_Term(class ClassOfStarCore *starcore)
++ {
++ return;
++ }


Android.mk:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

# Here we give our module name and sourcefile(s)
LOCAL_CFLAGS += -Wno-write-strings -DENV_ANDROID
LOCAL_CPPFLAGS += -Wno-write-strings -fexceptions -DENV_ANDROID
LOCAL_LDFLAGS += -Wno-write-strings -DENV_ANDROID

LOCAL_C_INCLUDES += ../../../../../android/workspace/include

#--------source file
MODULE_CXXSRCS := gl_code.cpp

LOCAL_SRC_FILES := ${MODULE_CXXSRCS}
LOCAL_LDLIBS := ../../../../../android/workspace/libs/armeabi/libstarlib.a -llog -lGLESv2

LOCAL_MODULE := gltest

include $(BUILD_SHARED_LIBRARY)

java code:

…
++ import com.srplab.www.starcore.*;
…
class GL2JNIView extends GLSurfaceView {
…

++ StarCoreFactory starcore;
++ static StarObjectClass GlObject;
…

private void init(boolean translucent, int depth, int stencil) {

…
++ StarCoreFactory starcore= StarCoreFactory.GetFactory();
++ StarServiceClass Service=starcore._InitSimple("test","123",0,0,"");
++ Service._CheckPassword(false);
++ Service._DoFile("","/data/data/com.srplabgl.gltest/lib/libgltest.so","");
++ GlObject = Service._GetObject("GLTestClass")._New();
…
}
…
private static class Renderer implements GLSurfaceView.Renderer {
public void onDrawFrame(GL10 gl) {
++ GlObject._Call("step");
}

public void onSurfaceChanged(GL10 gl, int width, int height) {
++ GlObject._Call("init",width,height);
}

public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Do nothing.
}
}

El código de ejemplo se puede descargar desde aquí .

En los casos más complicados, utilizando el método JNI será mucho más difícil porque los programadores tienen que gestionar las referencias, las devoluciones de llamada, las traducciones de los parámetros. Cle proporciona un método eficaz y flexible para Java llamada otros lenguajes como C / C + +.

La siguiente imagen es una biblioteca de envoltorio para Android de anti-grano GEOMET, que se publicará poco después.

Enviar y reciba parámetros con Android Para Mysql PHP

package com.phpserver;   import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;   import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;   public class send1 extends ListActivity {
int ct_id;
String[] ct_name = null;   @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
String result = null;
InputStream is = null;
StringBuilder sb = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8086/city.php");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// paring data
JSONArray jArray;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
ct_name = new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
ct_id = json_data.getInt("CITY_ID");
ct_name[i] = json_data.getString("CITY_NAME");
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
e1.printStackTrace();
}
setListAdapter(new ArrayAdapter<string>(this,
android.R.layout.simple_list_item_1, ct_name));
ListView lv;
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
ct_name[position] + " wasClicked", Toast.LENGTH_SHORT)
.show();
}   });
}
}</string>

-------------------------------------------------------------------------
código PHP para la recepción de los datos:


-------------------------------------------------------------------------


 

$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";   $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);   mysql_select_db("Deal");
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>


-------------------------------------------------------------------------
código de Java para Insertar datos


:-------------------------------------------------------------------------


 

 package com.Insert;   import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;   public class Insert extends ListActivity {
String[] ct_name = null;   @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);

InputStream is = null;
// http post
ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(); nameValuePairs.add(new BasicNameValuePair("c_name","KL"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8086/city1.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}

}


-------------------------------------------------------------------------
código PHP para Insertar datos:
-------------------------------------------------------------------------


 

 $hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";   $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);   mysql_select_db("Deal");
$sql=mysql_query("INSERT INTO CITY (CITY_NAME)VALUES('".$_REQUEST['c_name']."')");
//for updation
//$sql=update CITY set CITY_NAME='".$_REQUEST['c_name']."' where CITY_ID=22
$r=mysql_query($sql);
if(!$r)
echo "Error in query: ".mysql_error();
mysql_close();
?>


********************Add


 

 <uses-permission android:name="android.permission.INTERNET" xmlns:android="#unknown"></uses-permission>