Hi Guys!
I'm coding a little app, but I don't know what I'm doing wrong.
The App does the following:
- Launches a Service which listens for an sms, then captures a picture with the cam and sends it to a predefined email adress. (no, i'm not trying to spy somebody out... I'm using the app to get a "3G-Webcam", sort of at least)
The problem:
My App works great in the emulator, but as soon as I try it on my HTC Magic (cm6, android 2.2) it stops working.
logcat:
10-28 19:05:31.190: DEBUG/QualcommCameraHardware(91): createInstance: E
10-28 19:05:31.599: DEBUG/QualcommCameraHardware(91): createInstance: X created hardware=0x3bac0
10-28 19:05:31.719: ERROR/QualcommCameraHardware(91): native_set_dimension: length: 28.
10-28 19:05:31.769: DEBUG/QualcommCameraHardware(91): snapshot_thread E
10-28 19:05:35.939: DEBUG/skia(26561): purging 114K from font cache [11 entries]
10-28 19:05:36.270: DEBUG/dalvikvm(26561): JIT code cache reset in 2 ms (524208 bytes 1/0)
10-28 19:05:36.270: DEBUG/dalvikvm(26561): GC_EXPLICIT freed 15951 objects / 694856 bytes in 329ms
10-28 19:05:36.770: ERROR/QualcommCameraHardware(91): native_get_picture: MSM_CAM_IOCTL_GET_PICTURE fd 18 error Connection timed out
10-28 19:05:36.770: ERROR/QualcommCameraHardware(91): getPicture failed!
10-28 19:05:36.770: DEBUG/QualcommCameraHardware(91): snapshot_thread X
The permissions are all set, even the write to SD-card. What am I missing?
Note: I'm not using a surfaceview.
Code:
public void takePictureAndSendByMail() {
new Task().execute();
}
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
File storagepath = Environment.getExternalStorageDirectory();
filename = String.format(storagepath + "/%d.jpg", System.currentTimeMillis());
outStream = new FileOutputStream(filename);
outStream.write(data);
outStream.close();
Log.d("E", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d("E", "onPictureTaken - jpeg");
mCamera.release();
}
};
private class Task extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
}
protected Void doInBackground(Void... unused) {
try {
mCamera.takePicture(null, null, jpegCallback);
} catch (Exception e) {
Log.v("Error: ", "Exception", e);
}
return null;
}
protected void onPostExecute(Void unused) {
}
}
Click to expand...
Click to collapse
Related
I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
MidnightJava said:
I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
Click to expand...
Click to collapse
Afaik there's no way to accomplish that other than your way or being system/root app. See this similar question here for reference.
Can you show how you start the process?
EmptinessFiller said:
Can you show how you start the process?
Click to expand...
Click to collapse
Sure. Here's the class that manages starting, stopping, and statusing (running or not) the binary executable. In this case, it's the omniNames service of the omni ORB (CORBA broker).
Code:
public class RHManager {
private TimerTask task = new TimerTask() {
@Override
public void run() {
if (RHManager.this.listener != null) {
listener.running(isOmniNamesRunning());
}
}
};
private IStatusListener listener;
public RHManager() {
}
public void startOmniNames() {
final Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"start"};
final String[] env = new String[] {"LD_LIBRARY_PATH=/sdcard/data/com.axiosengineering.rhmanager/omniORB/lib"};
Thread t = new Thread() {
public void run() {
try {
int res = exec.doExec(args, env);
logMsg("omniNames start return code " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
}
String std = exec.getOutResult();
logMsg("omniNames start: std out==> " + std );
String err = exec.getErrResult();
logMsg("omniNames start: err out==> " + err );
};
};
t.start();
logMsg("omniNames started");
}
private boolean isOmniNamesRunning() {
String pid_s = getOmniNamesPid();
Integer pid = null;
if (pid_s != null) {
try {
pid = Integer.parseInt(pid_s);
} catch (NumberFormatException e) {
return false;
}
}
if (pid != null) {
RunningAppProcessInfo activityMgr = new ActivityManager.RunningAppProcessInfo("omniNames", pid, null);
return activityMgr.processName != null ;
}
return false;
}
public void stopOmniNames() {
String pid = getOmniNamesPid();
android.os.Process.killProcess(Integer.parseInt(pid));
android.os.Process.sendSignal(Integer.parseInt(pid), android.os.Process.SIGNAL_KILL);
}
private String getOmniNamesPid() {
Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"pid"};
String pid = "";
try {
int res = exec.doExec(args, null);
logMsg("oniNames pid return code: " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
return pid;
}
String std = exec.getOutResult();
logMsg("omniNames pid: std out ==> " + std);
String err = exec.getErrResult();
logMsg("omniNames pid: err out ==> " + err);
String[] parts = std.split("\\s+");
if (parts.length >= 2) {
pid = parts[1];
}
return pid;
}
//monitor omniNames status and report status periodically to an IStatusListener
public void startMonitorProcess(IStatusListener listener, String string) {
this.listener = listener;
Timer t = new Timer();
t.schedule(task, 0, 1000);
}
private void logMsg(String msg) {
if (RhMgrConstants.DEBUG) {
System.err.println(msg);
}
}
}
Here's the Exec class that handles invocation of Runtime#exec(), consumes std and err out, and reports those and process return status to the caller.
Code:
public class Exec {
private String outResult;
private String errResult;
private Process process;
private boolean failed = false;
StreamReader outReader;
StreamReader errReader;
public int doExec(String[] cmd, String[] envp) throws IOException{
Timer t = null;
try {
process = Runtime.getRuntime().exec(cmd, envp);
outReader = new StreamReader(process.getInputStream());
outReader.setPriority(10);
errReader = new StreamReader(process.getErrorStream());
outReader.start();
errReader.start();
t = new Timer();
t.schedule(task, 10000);
int status = process.waitFor();
outReader.join();
errReader.join();
StringWriter outWriter = outReader.getResult();
outResult = outWriter.toString();
outWriter.close();
StringWriter errWriter = errReader.getResult();
errResult = errWriter.toString();
errWriter.close();
return (failed ? -1: status);
} catch (InterruptedException e) {
return -1;
} finally {
if (t != null) {
t.cancel();
}
}
}
public int doExec(String[] cmd) throws IOException{
return doExec(cmd, null);
}
public String getOutResult(){
return outResult;
}
public String getErrResult(){
return errResult;
}
private static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter(30000);
}
public void run() {
try {
int c;
while ((c = is.read()) != -1){
sw.write(c);
}
}
catch (IOException e) { ; }
}
StringWriter getResult() {
try {
is.close();
} catch (IOException e) {
System.err.println("Unable to close input stream in StreamReader");
}
return sw;
}
}
private TimerTask task = new TimerTask() {
@Override
public void run() {
failed = true;
process.destroy();
}
};
}
Here's the script that startOminNames() invokes. It's the shell script installed with omniORB with functions other than start and get_pid removed, since those are handled by Android classes. You can invoke any executable in place of the script, or wrap your executable in a script.
Code:
#
# omniNames init file for starting up the OMNI Naming service
#
# chkconfig: - 20 80
# description: Starts and stops the OMNI Naming service
#
exec="/sdcard/data/com.axiosengineering.rhmanager/omniORB/bin/omniNames"
prog="omniNames"
logdir="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs"
logfile="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs/omninames-localhost.err.log"
options=" -start -always -logdir $logdir -errlog $logfile"
start() {
#[ -x $exec ] || exit 5
echo -n $"Starting $prog: "
$exec $options
}
get_pid() {
ps | grep omniNames
}
case "$1" in
start)
start && exit 0
$1
;;
pid)
get_pid
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?
And here's the IStatusListener interface
Code:
public interface IStatusListener {
public void running(boolean running);
}
Runtime.exec() has some pitfalls. See this helpful Runtime.exec tutorial for a nice explanation.
And you may also want to check out this post on loading native binaries in Android.
Hi, Dear XDA-developers,
Recently, I tried to build an blue tooth app. I wanted to display the data in the screen when all data arrived. I used the following code to do that job. However, the looping between Broadcaster receiver and Handler message could not be linked together smoothly. Usually, after one data displayed, I got an error with the following logs
02-03 05:01:30.931: W/dalvikvm(3419): threadid=11: thread exiting with uncaught exception (group=0x40018560)
02-03 05:01:37.827: E/AndroidRuntime(3419): FATAL EXCEPTION: Thread-13
02-03 05:01:37.827: E/AndroidRuntime(3419): java.lang.NullPointerException
02-03 05:01:37.827: E/AndroidRuntime(3419): at com.huasu.healthmonitor3.Device_Activity$1$2.run(Device_Activity.java:325)
02-03 05:01:37.827: E/AndroidRuntime(3419): at java.lang.Thread.run(Thread.java:1019)
the code snippet is as followings, any suggestions are appreciated!
public final Handler mHandler = new Handler() {
@override
public void handleMessage(Message msg) {
switch (msg.what) {
case Common.MESSAGE_CONNECT:
new Thread(new Runnable() {
public void run() {
InputStream tmpIn;
OutputStream tmpOut;
try {
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothDevice btDev = btAdapt
.getRemoteDevice(strAddress);
btSocket = btDev
.createRfcommSocketToServiceRecord(uuid);
btSocket.connect();
tmpIn = btSocket.getInputStream();
tmpOut = btSocket.getOutputStream();
} catch (Exception e) {
Log.d(Common.TAG, "Error connected to: "
+ strAddress);
bConnect = false;
mmInStream = null;
mmOutStream = null;
btSocket = null;
e.printStackTrace();
mHandler.sendEmptyMessage(Common.MESSAGE_CONNECT_LOST);
return;
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mHandler.sendEmptyMessage(Common.MESSAGE_CONNECT_SUCCEED);
}
}).start();
break;
case Common.MESSAGE_CONNECT_SUCCEED:
bConnect = true;
new Thread(new Runnable() {
public void run() {
// First write command to the bluetooth port
try{
mmOutStream.write(comm1);
}
catch (Exception e) {
Log.d(Common.TAG, "Error in writing command to bluetooth ");
}
int nRecv = 0;
while (bConnect) {
try {
Log.e(Common.TAG, "Start Recv" + String.valueOf(mmInStream.available()));
nRecv = mmInStream.read(bufRecv);
if (nRecv < 1) {
Log.e(Common.TAG, "Recving Short");
Thread.sleep(100);
continue;
}
System.arraycopy(bufRecv, 0, bRecv, nRecved, nRecv);
Log.e(Common.TAG, "Recv:" + String.valueOf(nRecv));
nRecved += nRecv;
if(nRecved < nNeed)
{
Thread.sleep(1000);
continue;
}
//sendBroadcast(intent);
mHandler.obtainMessage(Common.MESSAGE_RECV,nNeed, -1, null).sendToTarget();
} catch (Exception e) {
Log.e(Common.TAG, "Recv thread:" + e.getMessage());
mHandler.sendEmptyMessage(Common.MESSAGE_EXCEPTION_RECV);
break;
}
}
Log.e(Common.TAG, "Exit while");
}
}).start();
break;
case Common.MESSAGE_EXCEPTION_RECV:
case Common.MESSAGE_CONNECT_LOST:
try {
if (mmInStream != null)
mmInStream.close();
if (mmOutStream != null)
mmOutStream.close();
if (btSocket != null)
btSocket.close();
} catch (IOException e) {
Log.e(Common.TAG, "Close Error");
e.printStackTrace();
} finally {
mmInStream = null;
mmOutStream = null;
btSocket = null;
bConnect = false;
}
break;
case Common.MESSAGE_WRITE:
break;
case Common.MESSAGE_READ:
break;
case Common.MESSAGE_RECV:
Boolean bOn = false;
if(extr_validate_data())
{
bytesTofloat(bRec_out,3072);
broadcastIntent();
}
case Common.MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(Common.TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
private BroadcastReceiver connectDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(Common.TAG, "Receiver:" + action);
update_dis();
mHandler.obtainMessage(Common.MESSAGE_CONNECT_SUCCEED,nNeed, -1, null).sendToTarget();
}
};
public void broadcastIntent()
{
Intent intent = new Intent();
intent.setAction("com.huasu.healthmonitor3.draw");
sendBroadcast(intent);
}
It seems that the problematic part is in the Device_Activity.java at line 325. Could you post that line and lines around it here?
I am working on an Andriod project with Bluetooth LE. While BLE thread was scanning, this thread blocks other threads such as HTTP request and MediaPlayer . Http request is going to timeout or when i play music with meidplayer in app then app is freezing. I get this problem on thees android devices,Samsung Glaxy Tab SM-T700 and Samsung Galaxy TAB SM-T800. But i do not get this problem on Samsung Galaxy TAB SM-T520 device and any android phones.
Code:
BLE Scan Algorithm ` private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
ac.runOnUiThread(new Runnable() {
@Override
public void run() {
final BluetoothLeDevice deviceLe = new BluetoothLeDevice(
device, rssi, scanRecord, System
.currentTimeMillis());
// mDevices.add(deviceLe);
String rssiString = ac.getString(R.string.formatter_db,
String.valueOf(deviceLe.getRssi()));
if (tempDevice == null) {
tempDevice = deviceLe;
} else {
if (deviceLe.getRunningAverageRssi() > tempDevice
.getRunningAverageRssi()) {
IBeaconDevice newBeacon = new IBeaconDevice(
deviceLe);
IBeaconDevice bestDevice = new IBeaconDevice(
tempDevice);
if (newBeacon.getMajor() != bestDevice.getMajor()
|| newBeacon.getMinor() != bestDevice
.getMinor()) {
tempDevice = deviceLe;
}
}
}
}
// }
});
}
};` Music Play Algorithm . Mediaplayer is initialed before this code ` public void PlayPause() {
Log.e("Çalan", UrlSes);
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
}
try {
mediaPlayer.setDataSource(UrlSes); // setup song from
// http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
// URL to mediaplayer data
// source
mediaPlayer.prepare(); // you must call this method after setup the
// datasource in setDataSource method. After
// calling prepare() the instance of
// MediaPlayer starts load data from URL to
// internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the
// song
// length in
// milliseconds
// from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
imgPlay.setImageResource(R.drawable.footer_pause);
} else {
mediaPlayer.pause();
imgPlay.setImageResource(R.drawable.footer_play);
}
primarySeekBarProgressUpdater();
}` app freeze on mediplayer.prepare() I use mediplayer.prepareasync() but not plyaed . my web Request code `public JSONObject getJSONInfo(String functionName) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = null;
JSONObject send = new JSONObject();
try {
HttpPost post = new HttpPost(
""+url);
send.put("", variable1);
send.put("", variable1);
send.put("", variable2);
send.put("", variable1);
StringEntity se = new StringEntity(send.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
Log.e("test", send.toString());
post.setEntity(se);
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
json = new JSONObject(
EntityUtils.toString(response.getEntity()));
}
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
I'think This problem not about code or algorithm. Maybe about setting in device. Please help.
Same problem
Hi, did you find any solution for this ? I stucked on same problem and cant find how to solve this problem. :crying:
Thaks a lot for any advice.
Hello everyone, I have an Android application that allows users to choose a photo for their profile as follows:
public void pickImage(View view) {
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, 1);
}
@override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context context = getApplicationContext();
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
try {
ImageView im = findViewById(R.id.circularImageView);
uri = data.getData();
im.setImageURI(uri);
String image = uri.toString();
Log.d("ImageS", image);
SqlHelper db = new SqlHelper(this);
Intent i = getIntent();
String userid = i.getStringExtra("Name");
db.updateImage(userid, image);
}catch (Exception e){
}
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
Everything works fine and when I want to retrieve from my db the image everything works fine:
ImageView im1 = findViewById(R.id.circularImageView2);
im1.setImageURI(null);
String iS = db.getImage(name);
Log.d("ImageR", iS);
//
// Uri uri = Uri.parse(image);
//Log.d("Equals", String.valueOf(iS.equals(String.valueOf(R.drawable.imageuser))));
if(iS.equals(String.valueOf(R.drawable.imageuser))){ //Part to determine whether the user changed it or I use the default one
im1.setImageResource(Integer.parseInt(iS));
}else{
Uri uri = Uri.parse(iS);
ContentResolver contentResolver= getContentResolver();
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
try {
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
im1.setImageBitmap(image);
}
The thing is that when I restart the application, I get the following error when going into an activity in which a user changed the image:
FATAL EXCEPTION: main
Process: com.example.arturopavon.finalproject, PID: 1445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.arturopavon.finalproject/com.example.arturopavon.finalproject.MainActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{47cb71a 1445:com.example.arturopavon.finalproject/u0a294} (pid=1445, uid=10294) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{47cb71a 1445:com.example.arturopavon.finalproject/u0a294} (pid=1445, uid=10294) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.os.Parcel.readException(Parcel.java:2004)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:4827)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5843)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2526)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1783)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1396)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1249)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1102)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1056)
at com.example.arturopavon.finalproject.MainActivity.onCreate(MainActivity.java:126)
at android.app.Activity.performCreate(Activity.java:7026)
at android.app.Activity.performCreate(Activity.java:7017)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
I have permissions set for my app to read internal storage but it is like it is not working after rebooting.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.MANAGE_DOCUMENTS"/>
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MANAGE_DOCUMENTS};
for(String permission: permissions){
if (ContextCompat.checkSelfPermission(this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
permission)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
permissions, 0);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
Any ideas on how to solve this?
I think the gallery app gives you temporary access to the photo (search FLAG_GRANT_READ_URI_PERMISSION).
As the solution, you can copy the photo into application folder and keep it there.
Your logcat says "requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs".
Have a look in the following link. It should give you an idea or possible solution...
https://stackoverflow.com/a/22178386
Hi,
I have built a small notepad+barcodescanner app. Not it works, but the performance is low, as it processes all frames. It would be good if it would process only frams which are captured when the focus settled.
The app uses Camera2 PreviewBulder and CaptureRequestBuilder / RepeatingRequest, but i only found ways to get focus state during a Capturesession. (Capture is not used in this app, only getting frames from preview).
Does anyone how to process the focus state if one uses a Preview...?
Thanks for any help
Corresponding code part:
private final CameraDevice.StateCallback stateCallback = new
CameraDevice.StateCallback() {
@override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
// Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
@override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
@override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
@override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
// makeText(MainActivity.this, "Saved:" + file, LENGTH_SHORT).show();
createCameraPreview();
}
};
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(),
imageDimension.getHeight());
Surface surface = new Surface(texture);
CameraManager manager;
manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String camerId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(camerId);
boolean aelockavailable = characteristics.get(CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE);
}catch (Exception e)
{
}
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {
@override
public void onConfigured(@NonNull CameraCaptureSession
cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@override
public void onConfigureFailed(@NonNull
CameraCaptureSession cameraCaptureSession) {
//makeText(MainActivity.this, "Configuration change", LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
void openCamera() {
CameraManager manager = (CameraManager)
getSystemService(Context.CAMERA_SERVICE);
//Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics =
manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
//Log.e(TAG, "openCamera X");
}
void updatePreview() {
if (null == cameraDevice) {
//Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
if (flashchanged) {flashchanged=false; if (lamp && autoflash) {captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);} else {captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);} }
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),
null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}