Java 如何在以下代码中初始化变量位图?
我知道有这样一个关于堆栈溢出的问题 但是答案在我的代码中不起作用 我还尝试使用Java 如何在以下代码中初始化变量位图?,java,android-bitmap,Java,Android Bitmap,我知道有这样一个关于堆栈溢出的问题 但是答案在我的代码中不起作用 我还尝试使用decodeStream()获取 一个位图,但我只是得到相同的结果 唯一有效的方法是decodesource() 我不能使用解码资源,因为我需要 解码不断变化的图像,我会得到 在运行时,屏幕截图 以下所有代码都位于服务的onstartCommand()方法中 Notification.Builder notificationBuilder = new Notification.Builder(this) .se
decodeStream()
获取
一个位图,但我只是得到相同的结果
唯一有效的方法是decodesource()
我不能使用解码资源
,因为我需要
解码不断变化的图像,我会得到
在运行时,屏幕截图
以下所有代码都位于服务的onstartCommand()
方法中
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();
您确定您的应用程序清单(main/AndroidManifest.xml)包含android.permission.READ_外部_存储,并且您已在手机上授予此权限吗
在我的旧(根)手机上,一个示例应用程序未经此许可即可运行。在我更新的、没有根目录的手机上,我必须包含此权限才能使应用程序正常工作。您的img4.png包含字符串“/system/bin/screencap-p/data/data/com.mycompany.myapp/files/img4.png”(因为这是您写入该文件的内容)。您希望从这个字符串中看到什么图片?我肯定希望使用这一行(“/system/bin/screencap-p”+“/data/data/com.mycompany.myapp/files/img4.png”)将图像写入路径“/data/data/data/com.mycompany.myapp/files”).getBytes(“UTF-8”)。让我解释一下原因。一旦我得到了su的许可,这条线就会截屏并在某条路径上移动。我尝试了行(“/system/bin/screencap-p”+“/storage/emulated/0/myscreenshots/img4.png”).getBytes(“UTF-8”),它向路径/storage/emulated/0/myscreenshots写入了一个屏幕快照。这就是我将目录替换为私人位置的原因。请有人帮助。我愿意回答您可能有的任何问题。这个nullPointerException让我很紧张。如果您将该字符串写入
os
OutputStream(并因此将其作为命令提供给su
shell),它将编写一个映像。当代码保持不变时,您将其写入fos
。这是一个以“img4.png”为目标的FileOutputStream
。然后向我解释为什么这行,Bitmap Bitmap=BitmapFactory.decodeFile(“/storage/emulated/0/myimage.jpeg”);也没有创建位图,但我通过文件管理器手动将测试文件(确保它存在)放入我的目录根目录。