A Unity plugin to work with Android native sdk classes - IDEs, Libraries, & Programming Tools

I've started to work on this lib for our current project. But, maybe gamedev community will be interested in it.
Assume, you want to get your game version name and code. Yes, you will write something like this using AndroidJavaClass and AndroidJavaObject:
Code:
public static int GetVersionCode() {
AndroidJavaClass contextCls = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject context = contextCls.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject packageMngr = context.Call<AndroidJavaObject>("getPackageManager");
string packageName = context.Call<string>("getPackageName");
AndroidJavaObject packageInfo = packageMngr.Call<AndroidJavaObject>("getPackageInfo", packageName, 0);
return packageInfo.Get<int>("versionCode");
}
public static string GetVersionName() {
AndroidJavaClass contextCls = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject context = contextCls.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject packageMngr = context.Call<AndroidJavaObject>("getPackageManager");
string packageName = context.Call<string>("getPackageName");
AndroidJavaObject packageInfo = packageMngr.Call<AndroidJavaObject>("getPackageInfo", packageName, 0);
return packageInfo.Get<string>("versionName");
}
With this lib you can do same thing like this:
Code:
var activity = Internal.GetCurrentActivity();
var pm = activity.GetPackageManager();
var pi = pm.GetPackageInfo(activity.GetPackageName(), 0);
int code = pi.VersionCode;
string name = pi.VersionName;
There are not much you can do with this lib right now. But I'm going add new classes/methods from time to time.
I appreciate any feedback. Also, would be great if you star this repo :fingers-crossed:

Related

[Q] How to convert extended ASCII character to number in Android?

Hi!
Can you help me, please? I'm working on an Android app. I get some characters from a file on the Internet and put it to a TextView. These characters are ASCII characters. Then I read these characters one by one and convert it to numbers with the following code:
Code:
char my_char2;
char my_char3;
int myNum = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
myNum = my_char2 * 256 + my_char3;
}
}
Then I write it to an another TextView:
Code:
crlNumber.setText("" + myNum);
The problem is that this can only convert standard ASCII characters(from 0 to 127) except of the new line character(character number 10), carriage return character(character number 13) and the cancel character(character number 24).
But I need to convert also the extended ASCII characters(from 128 to 255) and the 3 characters mentioned above.
What should I do?
Thanks for helping.
Do these help?
http://stackoverflow.com/questions/13826781/java-extended-ascii-table-usage
http://stackoverflow.com/questions/5535988/string-to-binary-and-vice-versa-extended-ascii
nikwen said:
Do these help?
http://stackoverflow.com/questions/13826781/java-extended-ascii-table-usage
http://stackoverflow.com/questions/5535988/string-to-binary-and-vice-versa-extended-ascii
Click to expand...
Click to collapse
A little. I have tried the following code below. It didn't show me the number of the extended ascii characters. But I think I should somehow read the text not as a String, but as a byte, and then I think, it should work(maybe I am wrong). If it is right, please, can you tell me, how should I do it?
Code:
final String textSource = "path to my file";
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
String PT = textMsg.getText().toString();
CharSequence c = new String(PT);
String string0 = "";
String string1 = "";
char my_char2;
char my_char3;
String binary = "";
String binary2 = "";
int myNum2 = 0;
int decimalValue1 = 0;
int decimalValue2 = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
char[] buffer = string0.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
binary = Integer,toBinaryString(b[i] & 0xFF);
decimalValue1 = Integer.parseInt(binary, 2);
}
char[] buffer2 = string1.toCharArray();
byte[] b2 = new byte[buffer2.length];
for (int i = 0; i < b2.length; i++) {
b2[i] = (byte) buffer2[i];
binary2 = Integer.toBinaryString(b2[i] & 0xFF);
decimalValue2 = Integer.parseInt(binary2, 2);
}
myNum2 = decimalValue1 * 256 + decimalValue2;
}
}
crlNumber.setText("" + binary2 + "," + decimalValue1 + "," + decimalValue2 + "," + myNum2);
}
adamhala007 said:
A little. I have tried the following code below. It didn't show me the number of the extended ascii characters. But I think I should somehow read the text not as a String, but as a byte, and then I think, it should work(maybe I am wrong). If it is right, please, can you tell me, how should I do it?
Code:
final String textSource = "path to my file";
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
String PT = textMsg.getText().toString();
CharSequence c = new String(PT);
String string0 = "";
String string1 = "";
char my_char2;
char my_char3;
String binary = "";
String binary2 = "";
int myNum2 = 0;
int decimalValue1 = 0;
int decimalValue2 = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
char[] buffer = string0.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
binary = Integer,toBinaryString(b[i] & 0xFF);
decimalValue1 = Integer.parseInt(binary, 2);
}
char[] buffer2 = string1.toCharArray();
byte[] b2 = new byte[buffer2.length];
for (int i = 0; i < b2.length; i++) {
b2[i] = (byte) buffer2[i];
binary2 = Integer.toBinaryString(b2[i] & 0xFF);
decimalValue2 = Integer.parseInt(binary2, 2);
}
myNum2 = decimalValue1 * 256 + decimalValue2;
}
}
crlNumber.setText("" + binary2 + "," + decimalValue1 + "," + decimalValue2 + "," + myNum2);
}
Click to expand...
Click to collapse
Hm, I don't know. According to this answer, you can change the encoding on the desktop, otherwise you will just see question marks.
But according to the accepted answer here, this should be done automatically on a Linux system. And Android is Linux based. Did you try it on an Android device or just on your computer?
Bytes shouldn't work. In Java they are signed, so their range is -128 ... 127.
nikwen said:
Hm, I don't know. According to this answer, you can change the encoding on the desktop, otherwise you will just see question marks.
But according to the accepted answer here, this should be done automatically on a Linux system. And Android is Linux based. Did you try it on an Android device or just on your computer?
Bytes shouldn't work. In Java they are signed, so their range is -128 ... 127.
Click to expand...
Click to collapse
Yes, I tried it on my Android device. Maybe, the best choice would be then to use that certificate code which you suggested me in one of my previous threads, but the problem is, that I am beginner in Android developing and I read it and I didn't know how to use it in my code. So I thougt, if I got the 2 ASCII characters and converted it to decimal numbers, it would also work. And it also works until I have the standard ASCII characters. When there is an extended ASCII character, it shows me the number 65533.
adamhala007 said:
Yes, I tried it on my Android device. Maybe, the best choice would be then to use that certificate code which you suggested me in one of my previous threads, but the problem is, that I am beginner in Android developing and I read it and I didn't know how to use it in my code. So I thougt, if I got the 2 ASCII characters and converted it to decimal numbers, it would also work. And it also works until I have the standard ASCII characters. When there is an extended ASCII character, it shows me the number 65533.
Click to expand...
Click to collapse
But I think I have found out something.
Code:
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
int one = 0;
int two = 0;
String ascii1="\u001f";
String ascii2="\u0018";
String aa = "";
String bb = "";
if(string0.equals(ascii1)){
one = one + 31;
aa = aa + one;
}else{
one = 1;
}
if(string1.equals(ascii2)){
two = two + 24;
bb = bb + two;
}else{
two = 1;
}
textPrompt.setText("" + aa + bb);
But this needs a little correction, because this way it doesn't show me anything, but if I write
Code:
textPrompt.setText("" + aa);
inside my first if statement it shows me correctly 31. What can be the mistake I have made?
convert ASCII character
I'm a self android learner. I want to convert ascii code to character. Here is the code I used.
String s = "1000001";
int num = Integer.parseInt(s, 2);
TextView textView = new TextView(this);
textView.setText(String.valueOf(num));
setContentView(textView);
Here s is 1000001(65 in decimal) 65 is ascii value of 'A'. I want to get 'A' in my output screen.variable num has the value 65. please help me

[Q]What is the method name of this code block?

Hey guys I can't figure out the method name of this code block.
There are 2 more methods jus before it with the same "public BatteryMeterView".
the part in red what I want to change. Am using xposed code for it. Plz help asap.
Code:
public BatteryMeterView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources res = context.getResources();
TypedArray levels = res.obtainTypedArray(R.array.batterymeter_color_levels);
TypedArray colors = res.obtainTypedArray(R.array.batterymeter_color_values);
final int N = levels.length();
mColors = new int[2*N];
for (int i=0; i<N; i++) {
mColors[2*i] = levels.getInt(i, 0);
mColors[2*i+1] = colors.getColor(i, 0);
}
levels.recycle();
colors.recycle();
mShowPercent = ENABLE_PERCENT && 0 != Settings.System.getInt(
[COLOR=Red][B]context.getContentResolver(), "status_bar_show_battery_percent", 0);[/B][/COLOR]
mWarningString = context.getString(R.string.battery_meter_very_low_overlay_symbol);
mFramePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mFramePaint.setColor(res.getColor(R.color.batterymeter_frame_color));
mFramePaint.setDither(true);
mFramePaint.setStrokeWidth(0);
mFramePaint.setStyle(Paint.Style.FILL_AND_STROKE);
mFramePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
mBatteryPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBatteryPaint.setDither(true);
mBatteryPaint.setStrokeWidth(0);
mBatteryPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
[COLOR=Red][B] mTextPaint.setColor(0xFFFFFFFF);[/B][/COLOR]
Typeface font = Typeface.create("sans-serif-condensed", Typeface.NORMAL);
mTextPaint.setTypeface(font);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mWarningTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mWarningTextPaint.setColor(mColors[1]);
font = Typeface.create("sans-serif", Typeface.BOLD);
mWarningTextPaint.setTypeface(font);
mWarningTextPaint.setTextAlign(Paint.Align.CENTER);
mChargeColor = getResources().getColor(R.color.batterymeter_charge_color);
mBoltPaint = new Paint();
mBoltPaint.setAntiAlias(true);
mBoltPaint.setColor(res.getColor(R.color.batterymeter_bolt_color));
mBoltPoints = loadBoltPoints(res);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
SArnab©® said:
Hey guys I can't figure out the method name of this code block.
There are 2 more methods jus before it with the same "public BatteryMeterView".
the part in red what I want to change. Am using xposed code for it. Plz help asap.
Click to expand...
Click to collapse
Well the method is the constructor of the View, so it's name is exactly
Code:
BatteryMeterView(Context context, AttributeSet attrs, int defStyle)[\CODE]
Make sure you have the parameters as well since Java methods are only identical if they have the same return type, name and parameters. Not so sure how you would hook that method with xposed since I never did anything with it, but my guess would be to just copy the code from here to the method that runs before the hooked method, and then don't call that method at all. That way your method is larger but as the variables which you want to change are initialized right there it's the only way to do it.

Unable to upload picture when sending as Base64 String

I am trying to send an image to our asp.net webservice from android.Here is my sample code :
// Getting image from Gallery
Code:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
/* BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;*/
thumbnail = (BitmapFactory.decodeFile(picturePath));
img_photo.setImageBitmap(thumbnail);
// converting imag into base64 string
Code:
img_photo.buildDrawingCache();
Bitmap bm = img_photo.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap
byte[] photo = baos.toByteArray();
System.out.println("this is byte array" + bytearray);
String temp_base =Base64.encodeToString(photo,Base64.NO_WRAP);
// calling webservice
Code:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("CarID", SellCarDetailView.sellcardetails_carid);
request.addProperty("pic",temp_base);
System.out.println("this is piccontent" +temp_base);
try {
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
soapEnvelope.encodingStyle = SoapEnvelope.ENC;
// new MarshalBase64().register(soapEnvelope);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE aht = new HttpTransportSE(URL);
//AndroidHttpTransport aht = new AndroidHttpTransport(URL);
aht.call(SOAP_ACTION, soapEnvelope);
// SoapObject response = (SoapObject)envelope.getResponse();
SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse();
String temp3 = response.toString();
Log.v("TAG", temp3);
} catch (Exception e) {
e.printStackTrace();
}
How ever i am getting "invalid parameter" at web service end.
// Asp.net code
Code:
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Xml)]
[WebMethod(EnableSession = true)]
public string UploadPictureByCarIDFromAndroid(string CarID, string make, string model, string year, string UserID, string pic, string AuthenticationID, string CustomerID, string SessionID)
{
string bStatus = "Failed";
MobileBL objMobile = new MobileBL();
UsedCarsInfo objCarPicInfo = new UsedCarsInfo();
try
{
try
{
if (AuthenticationID == ConfigurationManager.AppSettings["AppleID"].ToString())
{
objCarPicInfo.Carid = Convert.ToInt32(CarID);
byte[] picContent = Convert.FromBase64String(pic);
// byte[] picContent = Base64.decode(pic);
MemoryStream ms = new MemoryStream(picContent, 0,picContent.Length); // getting "invalid length"
ms.Write(picContent, 0, picContent.Length);
Bitmap oBitmap1 = new Bitmap(ms);// getting "invalid length" error here
// System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
}
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
return bStatus;
}
I am getting "invalid length" error when sending the image.Any help is highly appreciated.
i think a better approach is with stream rather file path
for example you can try
Get image from gallery
Code:
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
//your options
Bitmap img_photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, options);
convert to base64
Code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img_photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String temp_base =Base64.encodeToString(byteArray,Base64.DEFAULT);
i cant see anything wrong in the web services call but shouldn't you send all the parameters the function needs?
also, try to change this
Code:
// SoapObject response = (SoapObject)envelope.getResponse();
SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse();
String temp3 = response.toString();
to this
Code:
SoapObject response = (SoapObject)envelope.getResponse();
String temp3 = response.getProperty(0).toString();
warlock9_0 said:
i think a better approach is with stream rather file path
for example you can try
Get image from gallery
Code:
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
//your options
Bitmap img_photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, options);
convert to base64
Code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img_photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String temp_base =Base64.encodeToString(byteArray,Base64.DEFAULT);
i cant see anything wrong in the web services call but shouldn't you send all the parameters the function needs?
also, try to change this
Code:
// SoapObject response = (SoapObject)envelope.getResponse();
SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse();
String temp3 = response.toString();
to this
Code:
SoapObject response = (SoapObject)envelope.getResponse();
String temp3 = response.getProperty(0).toString();
Click to expand...
Click to collapse
Thanks for giving reply, i tried your code but getting the same problem.
sending to web service is ok?
trying this in the web service end?
Code:
Bitmap bmpReturn = null;
byte[] byteBuffer = Convert.FromBase64String(base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
memoryStream.Close();
memoryStream = null;
byteBuffer = null;

[Q] Populate database in android 4.4 using phonegap?

I can't populate database in android 4.4 using phonegap when I run my app the first time, but if I close the app and open it again this task works fine.
I have a 0000000000000001.db in assets and I want put this in Android 4.4 memory.
How can I deal with such Issue?
I'm using this code to populate the database in Android 4.4 memory
Code:
public void copyDatabase(){
// DB_NAME2 = "Databases.db";
//ASSETS = "0000000000000001.db";
//DB_PATH2 = "/data/data/com.example.testapp/app_webview/databases/";
//DB_PATH3 = "/data/data/com.example.testapp/app_webview/databases/file__0/";
//DB_NAME3 = "1";
String path = DB_PATH2 + DB_NAME2;
String path2 = DB_PATH3 + DB_NAME3;
File checkDatabase = new File(DB_PATH2);
File checkDatabase2 = new File(DB_PATH3);
if (!checkDatabase.exists())
{
checkDatabase.mkdir();
}
if (!checkDatabase2.exists())
{
checkDatabase2.mkdir();
}
try{
InputStream is = context.getAssets().open(DB_NAME2);
OutputStream os = new FileOutputStream(path);
InputStream is2 = context.getAssets().open(ASSETS);
OutputStream os2 = new FileOutputStream(path2);
byte[] buffer = new byte[10240];
int line;
while ((line = is.read(buffer))>0)
{
os.write(buffer, 0, line);
}
os.flush();
os.close();
is.close();
buffer = new byte[10240];
line = 0;
while ((line = is2.read(buffer))>0)
{
os2.write(buffer, 0, line);
}
os2.flush();
os2.close();
is2.close();
}catch(IOException e){
System.out.println("Problem "+e);
}
}

$response JSON return only 1 row, PHP, ANDROID

When I use json_encode($response), it returns only the first row of the query, how to make it return all the rows?
main.php
Code:
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false ) {
// user found
$response["error"] = FALSE;
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["dega"] = $user["dega"];
$response["user"]["salla"] = $user["salla"];
$response["user"]["ora"] = $user["ora"];
$response["user"]["lenda"] = $user["lenda"];
$response["user"]["dita"] = $user["dita"];
echo json_encode($response);
}
method.php
Code:
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT U.name, U.email, U.password, F.dega,
O.salla, O.ora, O.lenda, O.dita FROM users U
INNER JOIN fakulteti F on U.id = F.studenti
INNER JOIN orari O on F.id = O.fakulteti WHERE email = '$email'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$encrypted_password = $result['password']
if ($encrypted_password == $password) {
return $result;
}
}
}
Android class and this is how I recieve a response on my android:
Code:
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String dega = user.getString("dega");
String salla = user.getString("salla");
String ora = user.getString("ora");
String lenda = user.getString("lenda");
String dita = user.getString("dita");
bump!!!!

Categories

Resources