Dynamically loading an external library at runtime - Java for Android App Development

I am using and android 2.2 phone for testing and getting an error which is driving me crazy
07-27 01:24:55.692: W/System.err(14319): java.lang.ClassNotFoundException: com.shoaib.AndroidCCL.MyClass in loader [email protected]
Can someone help me what to do now..i have tried various suggested solutions on different posts
First I wrote the following class:
Code:
package org.shoaib.androidccl;
import android.util.Log;
public class MyClass {
public MyClass() {
Log.d(MyClass.class.getName(), "MyClass: constructor called.");
}
public void doSomething() {
Log.d(MyClass.class.getName(), "MyClass: doSomething() called.");
}
}
And I packaged it in a DEX file that I saved on my device's SD card as `/sdcard/testdex.jar`.
Then I wrote the program below, after having removed `MyClass` from my Eclipse project and cleaned it:
Code:
public class Main extends Activity {
[user=1299008]@supp[/user]ressWarnings("unchecked")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
final String libPath = Environment.getExternalStorageDirectory() + "/testdex.jar";
final File tmpDir = getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("org.shoaib.androidccl.MyClass");
final Object myInstance = classToLoad.newInstance();
final Method doSomething = classToLoad.getMethod("doSomething");
doSomething.invoke(myInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
}

As far as I know you can't load external dex classes (and certainly not a jar file), the only ones that can be loaded are the ones packaged in the classes.dex file inside the APK and protected by its signature and certificate.
This would be quite a security flaw if your app could be "clean" at install but then download malicious classes and execute them.

Related

[Q] help on eclipse app

Hi guys,
First of all i`m completly noob on this so don`t be much hard with me
ok. i`m trying to develop a simple app just to run 4 simple command to install another app but for now the only thing that i can get to work was asking for su permissions...
can someone help me with this?
Thks a lot
HTML:
try {
runtime.exec("su -c busybox mount -o rw,remount /system");
runtime.exec("cp /sdcard/gscript/xrecovery.sh /data/local/tmp/xrecovery.sh");
runtime.exec("chmod 777 /data/local/tmp/xrecovery.sh");
runtime.exec("/data/local/tmp/xrecovery.sh");
runtime.exec("reboot");
}
catch (IOException e) {
e.printStackTrace();
do not think anyone has the knowledge to help me: .- (
My intention is to create a simple program that installs a file which is in sh sdcard,
"sdcard / gscript / xrecovery.sh"
until now could only be granted access to the root but do not know where and what command should I put to run that sh file...
is that no one can / want help?
thks
HTML:
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class xRecovery extends Activity {
Button app_name;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app_name = (Button)findViewById(R.id.TextView01);
xRecovery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {;
}
});
setContentView(R.layout.main);
try {
Runtime.getRuntime().exec("/sdcard/gscript/xrecovery.sh");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system\n" +
"exit \n");
os.flush();
process.waitFor();
}
Runtime.getRuntime().exec("/sdcard/gscript/xrecovery.sh");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected String[] getPackageResourcePath(String string) {
// TODO Auto-generated method stub
return null;
}
private static void setOnClickListener(OnClickListener onClickListener) {
// TODO Auto-generated method stub
}
}
You should be able to execute a .sh file by using:
Code:
sh xrecovery.sh
spolfliet said:
You should be able to execute a .sh file by using:
Code:
sh xrecovery.sh
Click to expand...
Click to collapse
Without sdcard path! ?
And where should i put?
Thks; )
Sent from my AOSP on Xperia (US) using XDA App
Of course you need to specify the path (it cannot guess where your script is, unless you add it to your PATH). So I guess the following should work for you:
Code:
Runtime.getRuntime().exec("sh /sdcard/gscript/xrecovery.sh");
Unfortunely i cant make this work UK sure that im putting the command Sony the wrong place. I've allready try put Sony a different pplaces but never work: (
Thks anyway; )
Sent from my AOSP on Xperia (US) using XDA App
really need help!
here is my complete code for what i want to do
HTML:
package com.rendeiro2005.xRecovery;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class xRecovery extends Activity {
Button INSTALL;
Button REMOVE;
AlertDialog.Builder builder;
AlertDialog Alert;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
Process process = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
DataInputStream inputStream = new DataInputStream(process.getInputStream());
outputStream.writeBytes("\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
process.waitFor();
process.waitFor();
if (process.exitValue() != 255) {
toastMessage("root");
}
else {
toastMessage("not root");
}
}
catch (IOException e)
{
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
catch (InterruptedException e)
{
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
INSTALL = (Button)findViewById(R.id.Button01);
REMOVE = (Button)findViewById(R.id.Button02);
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to install xRecovery?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Runtime.getRuntime().exec("sh /sdcard/gscript/xrecovery.sh");
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Alert = builder.create();
INSTALL.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Alert.show();
}
});
REMOVE.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
}
});
}
private void toastMessage(String string) {
}
}
i haven`t donne the uninstall part.
the problem here is everything work as it should exept the "sh" doesn`t do anything.
can anyone help me with this? i`m just trying to understand how the process works
thks a lot

stranges with android mediaservice

I've got nexus 4 and have some issue with media servicem cause my MS could not find music on my internal SD card; So I make an app;
Code:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
[user=439709]@override[/user]
public void onMediaScannerConnected() {
Log.v("MS", "connected");
mMs.scanFile(mFile.getAbsolutePath(), "audio/*");
Log.v("MS-file", mFile.getAbsolutePath());
}
[user=439709]@override[/user]
public void onScanCompleted(String path, Uri uri) {
mMs.disconnect();
}
}
Code:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath()+"/Music/");
for (int i=0;i<dir.listFiles().length;i++)
{
if (dir.listFiles()[i].isFile()==true&&dir.listFiles()[i].getName().endsWith(".mp3"))
{
new SingleMediaScanner(this, dir.listFiles()[i].getAbsoluteFile());
}
Log says that MS was connected and tried to scan media file, but file doesnt appear in Media library , what's the problem? by the way I have CM ROM

[Q] rmtp / mms player

hi friends
i can't play rtmp or mss protocol in android project (just audio live stream )
my code :
Code:
package sample.media.player;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
public class SampleMediaPlayerActivity extends Activity implements OnErrorListener, OnPreparedListener {
private MediaPlayer player;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("rtmp://199.103.63.202/live&file=irib3"); // rtmp link
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
[user=439709]@override[/user]
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
[user=439709]@override[/user]
public void onPrepared(MediaPlayer play) {
play.start();
}
[user=439709]@override[/user]
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
}
please help me / thanks:good:
Is it crashing or does it do nothing? Logcat?
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
help me plzzzzzzzzzzzz
nobodyyyyyy ????
takname said:
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
Click to expand...
Click to collapse
There should be more log code which is important. In every case there should be an Exception which is thrown.
I just found this library: http://www.aftek.com/afteklab/aftek-RTMP-library.shtml
Might be helpful.
(Both formats are not natively supported by the Android platform: http://developer.android.com/guide/appendix/media-formats.html)

[Q] Copy Image from Gallery Share (Send To) menu

Moderators... It says I am breaking the rules by asking a question and to ask in the Q&A... But the title of this is "Coding Discussion, Q&A, and Educational Resources" I am not breaking the rules intentionally, I just don't know where else to put this. This is a Coding Question, not a General Question that I would think would get buried and or lost in the General Q&A forum. Please move if you feel I am incorrect.
Hello All, I was hoping someone could help me.
I am trying to create an app that will hide pictures. I want to be able to Pick my App from the Share (Send To) menu from the Users Gallery and have it copy the file to a Directory I have created on my SDCard and then ultimately delete the file from the current location.
Here is what I have so far, but when I pick my app from the Share menu, it crashes the Gallery app. So... I can't even see any errors in my LogCat to even try and troubleshoot my issue.
Can someone point me to a working example of how to do this (I have searched the internet until I am blue in the face) or... I hate to say it... Fix my Code?
Any Help would be appreciated... Thanks!!
Code:
package com.company.privitegallery;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class SendToDo extends Activity {
File sdCardLoc = Environment.getExternalStorageDirectory();
File intImagesDir = new File(sdCardLoc,"/DCIM/privgal/.nomedia");
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
try {
GetPhotoPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
//...
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
public void GetPhotoPath() throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
copy(fileName, intImagesDir);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
try {
copy(selectedImagePath, intImagesDir);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(String scr, File dst) throws IOException {
InputStream in = new FileInputStream(scr);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void deleteLatest() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
//Log.i("Log", "file name in delete folder : "+f.toString());
File [] files = f.listFiles();
//Log.i("Log", "List of files is: " +files.toString());
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
// Log.i("Log", "Going -1");
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
// Log.i("Log", "Going +1");
return 1;
} else {
// Log.i("Log", "Going 0");
return 0;
}
}
});
//Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
files[0].delete();
}
}
What's the gallery log output?
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
nikwen said:
What's the gallery log output?
Click to expand...
Click to collapse
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
nikwen said:
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
Click to expand...
Click to collapse
Great, Thanks!!
StEVO_M said:
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
Great, Thanks!!
Click to expand...
Click to collapse
Do you view the logs on your computer?
There should be an error message in the logs.
nikwen said:
Do you view the logs on your computer?
There should be an error message in the logs.
Click to expand...
Click to collapse
Which Logs?? As I said before. LogCat does not give any errors.

[Q]Problem using RootTools library

i am trying to list files of root folders using roottools libary .here is the code
Code:
public ArrayList<File> listFiles(final Context c,final String path) {
final ArrayList<File> a=new ArrayList<File>();
Command command = new Command(0, "ls "+path)
{
@Override
public void commandOutput(int i, String s) {
File f=new File(path+"/"+s);
a.add(f);}
@Override
public void commandTerminated(int i, String s) {
}
@Override
public void commandCompleted(int i, int i2) {
//want to arraylist return from here
}
};
try {
RootTools.getShell(true).add(command);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
now problem is that if i return arraylist<file> from the end of method,its size is zero,to solve it i must return the arraylist from commandCompleted
method.but i am not able to accomplish that.So please solve my problem
Maybee arraylist as static outside your function? So on top of source file? Not sure but maybee

Categories

Resources