Camera2 focus state during preview - Java for Android App Development

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;
}
}

Related

Android ICS SSL Authentication Help

Im trying to build an RSS feed reader that needs to do some client side SSL authentication.
Ive got, or at least think i have, the certificate and now cannot figure out how to setup a ssl tunnel to send the certificate to the server to authenticate.
here is what i have so far:
public class Authenticator extends Activity {
PrivateKey privateKey = null;
String SavedAlias = "";
private static final String TAG = "AUTHENTICATOR.CLASS";
final HttpParams httpParams = new BasicHttpParams();
private KeyStore mKeyStore = KeyStore.getInstance();
public Handler mHandler = new Handler(Looper.getMainLooper());
public void run()
{
mHandler.post(new Runnable() {
public void run() {
new AliasLoader().execute();
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCertificates("TEST");
}
public class AliasLoader extends AsyncTask<Void, Void, X509Certificate[]>
{
X509Certificate[] chain = null;
@Override protected X509Certificate[] doInBackground(Void... params) {
android.os.Debug.waitForDebugger();
if(!SavedAlias.isEmpty())
{
try {
chain = KeyChain.getCertificateChain(getApplicationContext(),SavedAlias);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
else
{
this.cancel(true);
}
return chain;
}
@Override
protected void onPostExecute(X509Certificate[] chain)
{
if(chain != null)
{
Toast.makeText(getApplicationContext(), "YAY, Certificate is not empty", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Certificate is Empty", Toast.LENGTH_LONG).show();
}
/*
if (privateKey != null) {
Signature signature = null;
try {
signature = Signature.getInstance("SHA1withRSA");
} catch (NoSuchAlgorithmException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
try {
signature.initSign(privateKey);
} catch (InvalidKeyException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
*/
}
}
public void getCertificates(String Host)
{
KeyChainAliasCallback callBack = new KeyChainAliasCallback() {
@Override
public void alias(String alias) {
if (alias != null)
{
Looper.prepare();
saveAlias(alias);
run();
Looper.loop();
}
}
};
KeyChain.choosePrivateKeyAlias(this, callBack,
new String[] {"RSA", "DSA"}, // List of acceptable key types. null for any
null, // issuer, null for any
null, // host name of server requesting the cert, null if unavailable
443, // port of server requesting the cert, -1 if unavailable
null); // alias to preselect, null if unavailable
}
public void saveAlias(String alias)
{
SavedAlias = alias;
}
}
Any help on how to do this would be greatly appreciated as i have never done any authentication before and i have found it difficult to find anything on this topic for android 4.0 as 4.0 seems to be different in implementation then the older versions.

Retrieving cpu frequency

Hi everyone.
I want to retrieve the current cpu frequency in my app but I don't seem to be right.
In my code I want to read the "scaling_cpu_freq" file from internal storage.
This is the code:
Code:
private String ReadCPUMhz() {
String cpuMaxFreq = "";
int cur = 0;
try {
[user=1299008]@supp[/user]ressWarnings("resource")
BufferedReader maxi = new BufferedReader(new FileReader(new File("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")));
try{
cpuMaxFreq = maxi.readLine();
cur = Integer.parseInt(cpuMaxFreq);
cur = cur/1000;
} catch (Exception ex){
ex.printStackTrace();
}
} catch (FileNotFoundException f) {
f.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(cur);
}
The problem is that the method only returns 0, which is the initial value of the int "cur".
Can anybody help me?
Thanks in advance.
Here's the code I use:
Declare this class in your Activity
Code:
// Read current frequency from /sys in a separate thread
// This class assumes your TextView is declared and referenced in the OnCreate of the class this one is declared in
// And its variable name is mCurCpuFreq
protected class CurCPUThread extends Thread {
private static final String CURRENT_CPU = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
private boolean mInterrupt = false;
public void interrupt() {
mInterrupt = true;
}
[user=439709]@override[/user]
public void run() {
try {
while (!mInterrupt) {
sleep(400);
final String curFreq = readOneLine(CURRENT_CPU);
mCurCPUHandler.sendMessage(mCurCPUHandler.obtainMessage(0,
curFreq));
}
} catch (InterruptedException e) {
return;
}
}
}
// Update real-time current frequency & stats in a separate thread
protected static Handler mCurCPUHandler = new Handler() {
public void handleMessage(Message msg) {
mCurFreq.setText(toMHz((String) msg.obj));
final int p = Integer.parseInt((String) msg.obj);
new Thread(new Runnable() {
public void run() {
// Here I update a real-time graph of the current freq
}
}
}).start();
}
};
Helper methods used :
Code:
// Convert raw collected values to formatted MhZ
private static String toMHz(String mhzString) {
if (Integer.valueOf(mhzString) != null)
return String.valueOf(Integer.valueOf(mhzString) / 1000) + " MHz";
else
return "NaN";
}
// Iterate through the /sys file
public static String readOneLine(String fname) {
BufferedReader br;
String line = null;
try {
br = new BufferedReader(new FileReader(fname), 512);
try {
line = br.readLine();
} finally {
br.close();
}
} catch (Exception e) {
Log.e(TAG, "IO Exception when reading sys file", e);
// attempt to do magic!
return readFileViaShell(fname, true);
}
return line;
}
// Backup method if the above one fails
public static String readFileViaShell(String filePath, boolean useSu) {
CommandResult cr = null;
if (useSu) {
cr = new CMDProcessor().runSuCommand("cat " + filePath);
} else {
cr = new CMDProcessor().runShellCommand("cat " + filePath);
}
if (cr.success())
return cr.getStdout();
return null;
}
CMDProcessor.java and its dependencies attached to this post

[Q] Can I register a listener on process state?

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.

[Q] Threads exits with uncaught exception

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?

[Q] Android BLE Scan Blocks UI Threads

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.

Categories

Resources