John John - 1 month ago 5
Java Question

How can I initialise the variable bitmap in the following code?

I know there is such a question on Stack Overflow
but the answers just don't work in my code.

I have also tried using

decodeStream()
to get
a bitmap but I just get the same results.

The only method that works is
decodeResource()
.

I can't use
decodeResourse
because I need to
decode constantly changing images that I will get
at runtime, screenshots

All of the following code is in the
onstartCommand()
method of a service

Notification.Builder notificationBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = notificationBuilder.build();
mNotificationManager.notify(1, notification);
startForeground(1,notification);

String path = "/data/data/com.mycompany.myapp/files";
File f = null;
BitmapFactory.Options options = null;
Bitmap bitmap = null;
try{
//Request Su permission
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
//Open an output stream to a private file to my app
FileOutputStream fos = openFileOutput("img4.png", Context.MODE_PRIVATE);
fos.write(("/system/bin/screencap -p " +
"/data/data/com.mycompany.myapp/files/img4.png").getBytes("UTF-8"));
fos.close();

f=new File(path,"img4.png");
options = new BitmapFactory.Options();
options.inSampleSize = 4;
//decodeFile always returns null yet
//I am sure that the file exsists
bitmap = BitmapFactory.decodeFile(
new File(getFilesDir(),"img4.png").getAbsolutePath(),
options);
os.flush();
os.close();
sh.waitFor();
}catch(Exception e){
e.printStackTrace();
}
//I create and show a toast
Toast.makeText(getApplicationContext(),"Exs: " + f.exists()
//I always get a nullPointerException here
" "+ bitmap.getPixel(0,0),Toast.LENGTH_SHORT).show();

Answer

Are you sure that your applications manifest (main/AndroidManifest.xml) contains the android.permission.READ_EXTERNAL_STORAGE and that you have granted this permission on your phone?


On my old (rooted) phone a sample application worked without this permission. On my newer, not-rooted phone I had to include this permission to make the application work.