android12 createSurface Unable to set size,android11 is ok - android

This code used to be android11,but android12 video Unable to set size.Always full screen.Whatever size is set. How should I use it normally. The problem was discovered while upgrading the Android version.Please help me!thanks.android Why change the usage of the underlying interface. Is there any good in it.
void createSubSurface(int winSize[]){
int z_order = INT_MAX - 10;
int x_pos=0,y_pos=0 ,pip_width=960,pip_height =540;
const int numFds = 0;
const int numInts = 3;
x_pos = winSize[0];
y_pos = winSize[1];
pip_width = winSize[2];
pip_height = winSize[3];
printf(" createSurface pip start\n");
m_composerClient_pip = SurfaceComposerClient::getDefault();
m_composerClient_pip->initCheck();
#if 0
const sp<IBinder> display2 = SurfaceComposerClient::getInternalDisplayToken();
DisplayInfo info2;
if(display2 != NULL){
SurfaceComposerClient::getDisplayInfo(display2, &info2);
}
#endif
//surface 2
m_surfaceControl_pip = m_composerClient_pip->createSurface(String8("V1"),pip_width, pip_height, PIXEL_FORMAT_RGB_888, 0);
printf(" createSurface2 m_surfaceControl_pip !=NULL ? %d\n",m_surfaceControl_pip!=NULL);
if(m_surfaceControl_pip !=NULL && m_surfaceControl_pip->isValid()){
printf(" createSurface2 isValid == true\n");
SurfaceComposerClient::Transaction{}
.setLayer(m_surfaceControl_pip, z_order)
.setAlpha(m_surfaceControl_pip, 1.0f)
.setPosition(m_surfaceControl_pip,x_pos,y_pos)
.setSize(m_surfaceControl_pip, pip_width,pip_height)
.show(m_surfaceControl_pip)
.apply();
m_surface_pip = m_surfaceControl_pip->getSurface();
}
if(m_surface_pip !=NULL){
for (int k = 0; k < 10; k++)
{
int status =native_window_api_connect(m_surface_pip.get(),NATIVE_WINDOW_API_MEDIA);
printf(" createSurface2 status = %d\n",status );
handle2= native_handle_create(numFds, numInts);
handle2->data[numFds] = 1;
handle2->data[numFds + 1] = 1;
handle2->data[numFds + 2] = SidebandClient::DVDPLAYER_V2;
native_window_set_sideband_stream(m_surface_pip.get(), handle2);
if(status == 0){
break;
}else{
printf(" createSurface2 native_window_api_connect != OK\n");
}
usleep(200000);
}
}
printf("\n createSurface2 OK \n");
}

Related

Log variables being sent to control socket in Android

This question was migrated from Android Enthusiasts Stack Exchange because it can be answered on Stack Overflow.
Migrated 22 days ago.
I'm having a hard time trying to get /system/bin/raccoon to log the variables being sent to it through the control socket. I can get it to log with any variables sent to the command line just fine but when I try to use an external app sending the variables to /dev/socket/raccoon I can't see them. What am I doing wrong? Below is the code. Thanks in advance
My logging code
FILE *filepntr = fopen("/sdcard/log.txt", "w");
fprintf(filepntr, "\nThis line was for shits and giggles");
fprintf(filepntr, "*argc: %d\n", *argc );
fprintf(filepntr, "*argv[0]: %s\n", *argv[0] );
if ( *argc == 1 ) {
fprintf(filepntr, "No arguments were passed.\n" );
} else {
fprintf(filepntr, "Arguments:\n" );
for ( i = 1; i < *argc; ++i ) {
fprintf(filepntr, " %d. %s\n", i, *argv[i] );
}
}
Below is the app code:
static int android_get_control_and_arguments(int *argc, char ***argv)
{
static char *args[32];
int control;
int i;
atexit(notify_death);
if ((i = android_get_control_socket("racoon")) == -1) {
return -1;
}
do_plog(LLV_DEBUG, "Waiting for control socket");
if (listen(i, 1) == -1 || (control = accept(i, NULL, 0)) == -1) {
do_plog(LLV_ERROR, "Cannot get control socket");
exit(1);
}
close(i);
fcntl(control, F_SETFD, FD_CLOEXEC);
args[0] = (*argv)[0];
for (i = 1; i < 32; ++i) {
unsigned char bytes[2];
if (recv(control, &bytes[0], 1, 0) != 1 ||
recv(control, &bytes[1], 1, 0) != 1) {
do_plog(LLV_ERROR, "Cannot get argument length");
exit(1);
} else {
int length = bytes[0] << 8 | bytes[1];
int offset = 0;
if (length == 0xFFFF) {
break;
}
args[i] = malloc(length + 1);
while (offset < length) {
int n = recv(control, &args[i][offset], length - offset, 0);
if (n > 0) {
offset += n;
} else {
do_plog(LLV_ERROR, "Cannot get argument value");
exit(1);
}
}
args[i][length] = 0;
}
}
do_plog(LLV_DEBUG, "\n*Received %s Arguments");
*argc = i;
*argv = args;
return control;
}

How to Record audio using class AudioRecord in native c++

I used AudioRecord to record audio, following is my code:
#include<stdio.h>
#include<stdlib.h>
#include <media/AudioRecord.h>
using namespace android;
//==============================================
// Audio Record Defination
//==============================================
static pthread_t g_AudioRecordThread;
static pthread_t * g_AudioRecordThreadPtr = NULL;
volatile bool g_bQuitAudioRecordThread = false;
volatile int g_iInSampleTime = 0;
int g_iNotificationPeriodInFrames = 8000/10;
// g_iNotificationPeriodInFrames should be change when sample rate changes.
static void * AudioRecordThread( void *inArg );
void AudioRecordCallback(int event, void* user, void *info)
{
if(event == android::AudioRecord::EVENT_NEW_POS)
{
g_iInSampleTime += g_iNotificationPeriodInFrames;
//if(g_iInSampleTime > g_iNotificationPeriodInFrames*100)
// g_bQuitAudioRecordThread = true;
}
else if (event == android::AudioRecord::EVENT_MORE_DATA)
{
android::AudioRecord::Buffer* pBuff = (android::AudioRecord::Buffer*)info;
pBuff->size = 0;
}
else if (event == android::AudioRecord::EVENT_OVERRUN)
{
//LOGE(" EVENT_OVERRUN \n");
printf("[%d%s]EVENT_OVERRUN \n",__LINE__,__FUNCTION__);
}
}
static void * AudioRecordThread( void *inArg )
{
uint64_t inHostTime = 0;
void * inBuffer = NULL;
audio_source_t inputSource = AUDIO_SOURCE_MIC;
audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT;
audio_channel_mask_t channelConfig = AUDIO_CHANNEL_IN_MONO; //AUDIO_CHANNEL_IN_STEREO;
int bufferSizeInBytes = 1600;
int sampleRateInHz = 8000;
android::AudioRecord * pAudioRecord = NULL;
FILE * g_pAudioRecordFile = NULL;
//char strAudioFile[] = "/mnt/sdcard/external_sd/AudioRecordFile.pcm";
char strAudioFile[] = "./AudioRecordFile.pcm";
int iNbChannels = 1; // 1 channel for mono, 2 channel for streo
int iBytesPerSample = 2; // 16bits pcm, 2Bytes
int frameSize = 0; // frameSize = iNbChannels * iBytesPerSample
//int minFrameCount = 0; // get from AudroRecord object
size_t minFrameCount = 0; // get from AudroRecord object
int iWriteDataCount = 0; // how many data are there write to file
printf("[%d%s]thread enter ok!\n",__LINE__,__FUNCTION__);
String16 pack_name("wang_test");
printf("[%d%s]thread enter ok!\n",__LINE__,__FUNCTION__);
#if 1
// log the thread id for debug info
//LOGD("%s Thread ID = %d \n", __FUNCTION__, pthread_self());
printf("[%d%s] Thread ID = %d \n", __LINE__,__FUNCTION__, pthread_self());
g_iInSampleTime = 0;
g_pAudioRecordFile = fopen(strAudioFile, "wb+");
if(g_pAudioRecordFile == NULL)
{
printf("open file erro !\n");
}
iNbChannels = (channelConfig == AUDIO_CHANNEL_IN_STEREO) ? 2 : 1;
frameSize = iNbChannels * iBytesPerSample;
android::status_t status = android::AudioRecord::getMinFrameCount(
&minFrameCount, sampleRateInHz, audioFormat, channelConfig);
if(status != android::NO_ERROR)
{
//LOGE("%s AudioRecord.getMinFrameCount fail \n", __FUNCTION__);
printf("[%d%s]AudioRecord.getMinFrameCount fail \n",__LINE__,__FUNCTION__);
goto exit ;
}
//LOGE("sampleRateInHz = %d minFrameCount = %d iNbChannels = %d frameSize = %d ",
// sampleRateInHz, minFrameCount, iNbChannels, frameSize);
printf("[%d%s]sampleRateInHz = %d minFrameCount = %d iNbChannels = %d frameSize = %d \n",
__LINE__,__FUNCTION__,sampleRateInHz, minFrameCount, iNbChannels, frameSize);
bufferSizeInBytes = minFrameCount * frameSize;
inBuffer = malloc(bufferSizeInBytes);
if(inBuffer == NULL)
{
//LOGE("%s alloc mem failed \n", __FUNCTION__);
printf("[%d%s] alloc mem failed \n",__LINE__, __FUNCTION__);
goto exit ;
}
g_iNotificationPeriodInFrames = sampleRateInHz/10;
pAudioRecord = new android::AudioRecord(pack_name);
if(NULL == pAudioRecord)
{
//LOGE(" create native AudioRecord failed! ");
printf(" [%d%s] create native AudioRecord failed! \n",__LINE__,__FUNCTION__);
goto exit;
}
pAudioRecord->set( inputSource,
sampleRateInHz,
audioFormat,
channelConfig,
0,
AudioRecordCallback,
NULL,
0,
true);
if(pAudioRecord->initCheck() != android::NO_ERROR)
{
//LOGE("AudioTrack initCheck error!");
printf("[%d%s]AudioTrack initCheck error!\n",__LINE__,__FUNCTION__);
goto exit;
}
if(pAudioRecord->setPositionUpdatePeriod(g_iNotificationPeriodInFrames) != android::NO_ERROR)
{
//LOGE("AudioTrack setPositionUpdatePeriod error!");
printf("[%d%s]AudioTrack setPositionUpdatePeriod error!\n",__LINE__,__FUNCTION__);
goto exit;
}
if(pAudioRecord->start()!= android::NO_ERROR)
{
//LOGE("AudioTrack start error!");
printf("[%d%s]AudioTrack start error!\n",__LINE__,__FUNCTION__);
goto exit;
}
while (!g_bQuitAudioRecordThread)
{
//inHostTime = UpTicks();
int readLen = pAudioRecord->read(inBuffer, bufferSizeInBytes);
int writeResult = -1;
if(readLen > 0)
{
iWriteDataCount += readLen;
if(NULL != g_pAudioRecordFile)
{
writeResult = fwrite(inBuffer, 1, readLen, g_pAudioRecordFile);
if(writeResult < readLen)
{
//LOGE("Write Audio Record Stream error");
printf("[%d%s]Write Audio Record Stream error\n",__LINE__,__FUNCTION__);
}
}
// write PCM data to file or other stream,implement it yourself
//writeResult = WriteAudioData(
// g_iInSampleTime,
// inHostTime,
// inBuffer,
// readLen);
//LOGD("readLen = %d writeResult = %d iWriteDataCount = %d", readLen, writeResult, iWriteDataCount);
}
else
{
//LOGE("pAudioRecord->read readLen = 0");
printf("[%d%s]pAudioRecord->read readLen = 0\n",__LINE__,__FUNCTION__);
}
}
exit:
if(NULL != g_pAudioRecordFile)
{
fflush(g_pAudioRecordFile);
fclose(g_pAudioRecordFile);
g_pAudioRecordFile = NULL;
}
if(pAudioRecord)
{
pAudioRecord->stop();
//delete pAudioRecord;
pAudioRecord == NULL;
}
if(inBuffer)
{
free(inBuffer);
inBuffer = NULL;
}
#endif
//LOGD("%s Thread ID = %d quit\n", __FUNCTION__, pthread_self());
printf("[%d%s] Thread ID = %d quit\n", __LINE__,__FUNCTION__, pthread_self());
return NULL;
}
int main()
{
printf("hello world! \n");
pthread_t record_pid ;
if(pthread_create(&record_pid,NULL,AudioRecordThread,NULL)<0)
{
printf("%d%s pthread create erro !\n",__LINE__,__FUNCTION__);
}
while(1)
{
}
return 0;
}
I pushed the executable file under /data directory. After running it, i get the pcm file. I used Cool Pro Edit software to play it, however i couldn't hear anything.

Arabic PDF Text Extractor

Is there any pdf text extractor api that extract arabic text from pdf.
I am using itextpdf api it works fine in extract English but it doesn't extract arabic text.
This is my code for extract text in pdf:
private String extractPDF(String path) throws IOException {
String parsedText = "";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
for (int page = 0; page < n; page++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, page + 1).trim() + "\n"; //Extracting the content from the different pages
}
reader.close();
return parsedText;
}
and this is the input pdf :arabic.pdf
Update :
i able to extract arabic text but it doesn't preserves the order of the lines , and this is my code:
private String extractPDF(String name) throws IOException {
PdfReader reader = new PdfReader(name);
StringBuilder text = new StringBuilder();
for (int i=1;i<=reader.getNumberOfPages();i++){
String data = PdfTextExtractor.getTextFromPage(reader,i,new SimpleTextExtractionStrategy());
text.append(Bidi.BidiText(data,1).getText());
}
return text.toString();
}
pdf text is :
بسم الله الرحمن الرحيم
السلام عليكم ورحمة الله وبركاته
سبحان الله
the output is :
سبحان الله
السلام عليكم ورحمة الله وبركاته
بسم الله الرحمن الرحيم
this is my code for method BidiText:
public static BidiResult BidiText(String str, int startLevel)
{
boolean isLtr = true;
int strLength = str.length();
if (strLength == 0)
{
return new BidiResult(str, false);
}
// get types, fill arrays
char[] chars = new char[strLength];
String[] types = new String[strLength];
String[] oldtypes = new String[strLength];
int numBidi = 0;
for (int i = 0; i < strLength; ++i)
{
chars[i] = str.charAt(i);
char charCode = str.charAt(i);
String charType = "L";
if (charCode <= 0x00ff)
{
charType = BaseTypes[charCode];
}
else if (0x0590 <= charCode && charCode <= 0x05f4)
{
charType = "R";
}
else if (0x0600 <= charCode && charCode <= 0x06ff)
{
charType = ArabicTypes[charCode & 0xff];
}
else if (0x0700 <= charCode && charCode <= 0x08AC)
{
charType = "AL";
}
if (charType.equals("R") || charType.equals("AL") || charType.equals("AN"))
{
numBidi++;
}
oldtypes[i] = types[i] = charType;
}
if (numBidi == 0)
{
return new BidiResult(str, true);
}
if (startLevel == -1)
{
if ((strLength / numBidi) < 0.3)
{
startLevel = 0;
}
else
{
isLtr = false;
startLevel = 1;
}
}
int[] levels = new int[strLength];
for (int i = 0; i < strLength; ++i)
{
levels[i] = startLevel;
}
String e = IsOdd(startLevel) ? "R" : "L";
String sor = e;
String eor = sor;
String lastType = sor;
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("NSM"))
{
types[i] = lastType;
}
else
{
lastType = types[i];
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("AL")) ? "AN" : "EN";
}
else if (t.equals("R") || t.equals("L") || t.equals("AL"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("AL"))
{
types[i] = "R";
}
}
for (int i = 1; i < strLength - 1; ++i)
{
if (types[i].equals("ES") && types[i - 1].equals("EN") && types[i + 1].equals("EN"))
{
types[i] = "EN";
}
if (types[i].equals("CS") && (types[i - 1].equals("EN") || types[i - 1].equals("AN")) && types[i + 1] == types[i - 1])
{
types[i] = types[i - 1];
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("EN"))
{
// do before
for (int j = i - 1; j >= 0; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
// do after
for (int j = i + 1; j < strLength; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("WS") || t.equals("ES") || t.equals("ET") || t.equals("CS"))
{
types[i] = "ON";
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("L")) ? "L" : "EN";
}
else if (t.equals("R") || t.equals("L"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
int end = FindUnequal(types, i + 1, "ON");
String before = sor;
if (i > 0)
{
before = types[i - 1];
}
String after = eor;
if (end + 1 < strLength)
{
after = types[end + 1];
}
if (!before.equals("L"))
{
before = "R";
}
if (!after.equals("L"))
{
after = "R";
}
if (before == after)
{
SetValues(types, i, end, before);
}
i = end - 1; // reset to end (-1 so next iteration is ok)
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
types[i] = e;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (IsEven(levels[i]))
{
if (t.equals("R"))
{
levels[i] += 1;
}
else if (t.equals("AN") || t.equals("EN"))
{
levels[i] += 2;
}
}
else
{
if (t.equals("L") || t.equals("AN") || t.equals("EN"))
{
levels[i] += 1;
}
}
}
int highestLevel = -1;
int lowestOddLevel = 99;
int ii = levels.length;
for (int i = 0; i < ii; ++i)
{
int level = levels[i];
if (highestLevel < level)
{
highestLevel = level;
}
if (lowestOddLevel > level && IsOdd(level))
{
lowestOddLevel = level;
}
}
for (int level = highestLevel; level >= lowestOddLevel; --level)
{
int start = -1;
ii = levels.length;
for (int i = 0; i < ii; ++i)
{
if (levels[i] < level)
{
if (start >= 0)
{
chars = ReverseValues(chars, start, i);
start = -1;
}
}
else if (start < 0)
{
start = i;
}
}
if (start >= 0)
{
chars = ReverseValues(chars, start, levels.length);
}
}
String result = "";
ii = chars.length;
for (int i = 0; i < ii; ++i)
{
char ch = chars[i];
if (ch != '<' && ch != '>')
{
result += ch;
}
}
return new BidiResult(result, isLtr);
}
Your example PDF does not contain any text at all, it merely contains an embedded bitmap image of text.
When talking about "text extraction from PDFs" (and "text extractor APIs" and PdfTextExtractor classes etc.), one usually means finding text drawing instructions in the PDF (for which a PDF viewer uses a font program either embedded in the PDF or available on the system at hand to display the text) and determining their text content from their string arguments and font encoding definitions.
As in your case there are no such text drawing instructions, merely a bitmap drawing instruction and the bitmap itself, text extraction from your document will return an empty string.
To retrieve the text displayed in your document, you have to look for OCR (optical character recognition) solutions. PDF libraries (like iText) can help you to extract the embedded bitmap image to forward to the OCR solution if the OCR solution does not directly support PDF but only bitmap formats.
If you also have PDF documents which display Arabic text using text drawing instructions with sufficient encoding information instead of bitmaps, you may need to post-process the text extraction output of iText with a method like Convert as proposed in this answer as pointed out by Amedee in a comment to your question. (Yes, it is written in C# but it is pretty easy to port to Java.)

android bluetooth LE, how to get RR interval

i'm developing an android application uses bluetooth LE, i need to get RR interval. I start form this example on android developer site:
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// This is special handling for the Heart Rate Measurement profile. Data
// parsing is carried out as per profile specifications.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG, "Heart rate format UINT8.");
}
final int heartRate = characteristic.getIntValue(format, 1);
Log.d(TAG, String.format("Received heart rate: %d", heartRate));
intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
} else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" +
stringBuilder.toString());
}
}
sendBroadcast(intent);
}
How i can get RR interval? I just do it with iOS, but on java i don't know how to do..
this is my code on iOS, and works perfectly:
- (void) updateWithHRMData:(NSData *)datas {
const uint8_t *reportData = [datas bytes];
uint16_t bpm = 0;
uint16_t bpm2 = 0;
if ((reportData[0] & 0x04) == 0)
{
NSLog(#"%#", #"Data are not present");
}
else
{
bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[2]));
bpm2 = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[4]));
if (bpm != 0 || bpm2 != 0) {
self.deviceReady = true;
[lblNofascia setAlpha:0.0];
[btnMonitor setAlpha:1.0];
if (isRunning) {
[self.elencoBattiti addObject:[NSString stringWithFormat:#"%u", bpm]];
NSLog(#"%u", bpm);
if (bpm2 != 0) {
[self.elencoBattiti addObject:[NSString stringWithFormat:#"%u", bpm2]];
NSLog(#"%u", bpm2);
}
}
} else {
if (isRunning) {
totErrori++;
NSLog(#"Dato non trasmesso");
if (totErrori > 5) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Attenzione" message:#"Ho perso la connettività con la fascia. Ripetere la misurazione" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Continua", nil];
[alert show];
[self stopRunning];
}
}
}
}
}
thank you
I have the following.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
int format = -1;
int energy = -1;
int offset = 1;
int rr_count = 0;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Logger.trace("Heart rate format UINT16.");
offset = 3;
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Logger.trace("Heart rate format UINT8.");
offset = 2;
}
final int heartRate = characteristic.getIntValue(format, 1);
Logger.trace("Received heart rate: {}", heartRate);
if ((flag & 0x08) != 0) {
// calories present
energy = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
offset += 2;
Logger.trace("Received energy: {}", energy);
}
if ((flag & 0x10) != 0){
// RR stuff.
rr_count = ((characteristic.getValue()).length - offset) / 2;
for (int i = 0; i < rr_count; i++){
mRr_values[i] = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
offset += 2;
Logger.trace("Received RR: {}", mRr_values[i]);
}
}
Thanks Ifor. With some fixes the android code should work. The bit mask for RR data flag should be 16 according to specs and the array should be declared:
if ((flag & 0x16) != 0){
// RR stuff.
rr_count = ((characteristic.getValue()).length - offset) / 2;
Integer[] mRr_values = new Integer[rr_count];
for (int i = 0; i < rr_count; i++){
mRr_values[i] = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
offset += 2;
Logger.trace("Received RR: {}", mRr_values[i]);
}
}

create a substitute of Uint8array on android 2.x

I'm developping an application on phonegap for android. I would like that the application can work on android 2.3.3 and more.
I use Uint8array on my code. this work on android 4 but not on android 2. I've got this error:
can't find variable: Uint8array
I do some research and found that uint8array is not supported on android2. I would like to know if there is a similiar function or a library that work on android 2.
Thank you
I've got the answer.
you have to create a js file. In this one paste this code:
(function() {
try {
var a = new Uint8Array(1);
return; //no need
} catch(e) { }
function subarray(start, end) {
return this.slice(start, end);
}
function set_(array, offset) {
if (arguments.length < 2) offset = 0;
for (var i = 0, n = array.length; i < n; ++i, ++offset)
this[offset] = array[i] & 0xFF;
}
// we need typed arrays
function TypedArray(arg1) {
var result;
if (typeof arg1 === "number") {
result = new Array(arg1);
for (var i = 0; i < arg1; ++i)
result[i] = 0;
} else
result = arg1.slice(0);
result.subarray = subarray;
result.buffer = result;
result.byteLength = result.length;
result.set = set_;
if (typeof arg1 === "object" && arg1.buffer)
result.buffer = arg1.buffer;
return result;
}
window.Uint8Array = TypedArray;
window.Uint32Array = TypedArray;
window.Int32Array = TypedArray;
})();
(function() {
if ("response" in XMLHttpRequest.prototype ||
"mozResponseArrayBuffer" in XMLHttpRequest.prototype ||
"mozResponse" in XMLHttpRequest.prototype ||
"responseArrayBuffer" in XMLHttpRequest.prototype)
return;
Object.defineProperty(XMLHttpRequest.prototype, "response", {
get: function() {
return new Uint8Array( new VBArray(this.responseBody).toArray() );
}
});
})();
(function() {
if ("btoa" in window)
return;
var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
window.btoa = function(chars) {
var buffer = "";
var i, n;
for (i = 0, n = chars.length; i < n; i += 3) {
var b1 = chars.charCodeAt(i) & 0xFF;
var b2 = chars.charCodeAt(i + 1) & 0xFF;
var b3 = chars.charCodeAt(i + 2) & 0xFF;
var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
buffer += digits.charAt(d1) + digits.charAt(d2) + digits.charAt(d3) + digits.charAt(d4);
}
return buffer;
};
})();
And just include this javascript before you use UInt8array

Categories

Resources