continuous sending of data - android

The android application is bulit in such a way that when data is being sent(on clicking the button) to the usb device ,LED toggles and the data is being displayed. I want data to be sent continuously without any manual intervention. Kindly help
if (mInputStream != null)
{
int Data = 0;
try {
Data = mInputStream.read();
} catch (IOException e) {
}
if (Data == LED_ON)
{
ledStatus.setText("LED is ON");
}
else if (Data == LED_OFF)
{
ledStatus.setText("LED is OFF");
}
else
{
ledStatus.setText("Request failed");
}
}
else
{
ledStatus.setText("mInputStream == null");
}

this time I have tested it myself...
it should definitely work
paste it in your onCreate() good luck :)
Timer t = new Timer();
t.schedule(new TimerTask(){
public void run(){
// write the method name here. which you want to call continuously
Log.d("timer", "timer");
}
},10, 1000);

Related

How can I read all characteristic of a BLE device with Queque List in a for cycle?

Im' building an app that download all information from a BLE device. This device, can storage the information in your flash memory. The BLE device have 2 characteristic. So I'm building a code to download all information from it.
I have create a Queque of charactersitic to read, then I have a for cycle to read these characteristic.
To do this, I have implement a class that extends "Service"
This is my code:
TimerTask timerTask = new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void run() {
continuaLetturaForza = true;
continuaLetturaTemperatura = true;
int counter = 0;
while(continuaLetturaForza || continuaLetturaTemperatura){
counter++;
Log.v("CICLO WHILE", counter+"");
if (currDevice != null) {
if(ReadQueue!= null && ReadQueue.size()>0){
for(int index=0; index< ReadQueue.size(); index++){
mGatt.readCharacteristic(ReadQueue.get(index));
/*try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
}else{
//TO DO
}
}
if(gattClientCallback!=null && mGatt != null)
gattClientCallback.disconnectGattServer();
}
};
If I try to start my application, I can see ReadQueque List with my two characteristic, so I read characteristic 1 and characteristic 2 but effectively the system real only the first characteristic.
But if I uncomment this line of code:
/*try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
all system found and I can read Characteristic 1 and 2. If I don't insert Thread.sleep, I read only the first characteristic.
Why ?

Releasing the camera within a thread

I am creating a simple Morse code app. The user can enter in text which is then translated to Morse and flashed in sequence on a new thread. I have implemented a for loop which is used to turn on/off the camera flash to represent the Morse sequence.
The problem is that when the user navigates away from the activity the on pause method releases the camera but i sometimes get the error 'method called after release'. I am not sure how to cancel the thread from running when the camera is released. I have already attempted to use a volatile Boolean value which is checked at the start of each loop iteration but if the loop is cancelled at any other time but the start then it results in an error.
Does anyone have any ideas/suggestions as to how i could solve this problem?
public void flashTranslation(String message) {
int offIntervalTime = 50;
char[] cArray = message.toCharArray();
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == '.') {
turnOn();
try {
Thread.sleep(50);
}catch(Exception e)
{
Log.d("One", "Two");
}
turnOff();
try {
Thread.sleep(offIntervalTime);
}catch(Exception e)
{
}
} else if(cArray[i] == ' ')
{
Log.d("EMPTY!", "EMPTY!");
try{
Thread.sleep(100);
}catch(Exception e)
{
}
}
else {
try{
turnOn();
Thread.sleep(dash);
}catch(Exception e)
{
}
try{
turnOff();
Thread.sleep(offIntervalTime);
}catch(Exception e)
{
}
}
}
}
The easiest way to do this is canceling the thread protecting against concurrent access via semaphore. Every time you try to flash on the thread, you check if the thread is canceled. Pseudocode:
Semaphore sem;
onPause(){
sem.take();
camera.turnOff();
camera.release();
thread.cancel();
sem.give();
}
thread.run() {
//This should be run before every call to turnOn or turnoff
sem.take();
if(isCanceled()) {
return;
}
turnOn();
sem.give();
}
onResume() {
new Thread.start();
}

Write NDEF message inside a loop

I want to write different NDEF messages inside a while() loop.
LAST EDIT: It seems that the microcontroller can't process data so fast, so my problem cannot be solved.
//ndef.connect();
ndef.writeNdefMessage(message);
//ndef.close();
My write() method, simplified, without all try/catch
So, at first loop it works correctly, but next ones don't. But after a number of loops it works again for one more time. This repeats.
stop = 0;
while(stop < 1000)
{
write();
stop++
}
write() is working correctly for one loop.
EDIT: I replaced while() with a timer:
new Timer().schedule(new TimerTask() {
#Override
public void run() {
write();
}
}, 2000);
But this is too slow... I need to write at least 5 times per second.
If I set timer period less than 2000 it doesn't work, works same as while()
EDIT2: I measured how fast a message is transmitted and received. It seems it takes about 55ms to send a message, and about 7ms to receive. This is what I want, but if I set my timer to repeat after 100ms, for example, I have this error from writeNDEFmessage() :
java.io.IOException: Tag is not ndef . So if I loop 10 times writeNDEFmessage() it works fine at first loop but I receive exception at the following 9.
EDIT3:
onNewIntent() :
#Override
protected void onNewIntent(Intent intent)
{
try {
if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED) ||
intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)||
intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED))
{
detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if(detectedTag != lastDetectedTag)
{
lastDetectedTag = detectedTag;
setIntent(intent);
}
}
} catch (Exception e)
{
Log.e("", "onIntent >>> "+e.getMessage());
}
}
This is assigned to a button:
public void testWrite()
{
final Timer timer = new Timer();
try {
ndef = Ndef.get(detectedTag);
ndef.connect();
} catch (IOException e) {
Log.e("", "Cannot connect");
e.printStackTrace();
}
timer.schedule(new TimerTask() {
#Override
public void run() {
transmit.writeTag(message), ndef)
}, 0, 200);
}
and writeTag():
public boolean writeTag(String str, Ndef ndef) {
try {
message = getNdefMessage(str);
}
catch (Exception e)
{
toast("Message error");
}
int size = message.toByteArray().length;
try {
if (ndef != null) {
if(!ndef.isConnected())
{
ndef.connect();
Log.e("", ""+ndef.toString());
}
if (!ndef.isWritable()) {
return false;
}
if (ndef.getMaxSize() < size) {
toast("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.");
return false;
}
try{
ndef.writeNdefMessage(message);
}
catch(IOException e){
toast("error send");
Log.e("IOException", e + "-+-");
return false;
}
return true;
}
}
catch (Exception e) {
toast("Failed to write tag");
}
return false;
}
transmit is an object from Transmit class, in which writeTag() is defined
onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
transmit = new Transmit(this);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
textView.setText("");
detectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
lastDetectedTag = detectedTag;
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this, getClass()).
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
readTagFilters = new IntentFilter[]{tagDetected,filter2};
techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
if (mNfcAdapter == null) {
// Stop here, we definitely need NFC
finish();
return;
}
if (!mNfcAdapter.isEnabled()) {
}
buttonListener(testButton);
}
From the Ndef docs for the close() method: "Disable I/O operations to the tag from this TagTechnology object, and release resources."
So I think when you call close() the internal TagTechnology is released. If you call connect on the same ndef it's a "stale" object. Try creating a new Ndef object each time by passing it the Tag object.
Edit: Or else just don't call close() until you're actually finished. You will still need to call connect() the first time. Additionally I'd always call isConnected() first to ensure the tag is present and connected.

License Check Loop?

Maybe the code kind of shows what I'm attempting to do, so I'll start with that
private void getLicenseResults() {
if (licensed && didCheck == true) {
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"***.MAINACTIVITY");
startActivity(openStartingPoint);
finish();
}
}
};
timer.start();
}
if (didCheck == false) {
Toast.makeText(Splash.this, "Checking License, Please Wait",
Toast.LENGTH_LONG).show();
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
getLicenseResults();
Log.i("LICENSE", "re-checking");
}
}
};
timer.start();
}
}
I ran the license check without trying to loop it before, and it worked except if the checking took more than a couple seconds it skipped over the
if (licensed && didCheck == true)
and the activity just kind of stood and waited without launching my main activity (this check is on the splash screen).
So I want the "if didCheck = true" part to be called only after didCheck is in fact finally true. I'm sure there's an easy solution, but I'm self-taught and I have no experience with loops or callbacks(?).
Thank you for any help!
You are not setting didCheck to true in your second if statement before the call to getLicenseResults

AsyncTask with Timer keeps on running

I have scheduled a AsyncTask using a Timer by following code
public void toCallAsynchronous() {
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
if(mLoggedIn)
{
DownloadRandomPicture download = new DownloadRandomPicture(this, mApi, CLIENT_ID, mImage);
download.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms
}
#Override
protected Boolean doInBackground(Void... params) {
try {
if (mCanceled) {
return false;
}
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null) {
// It's not a directory, or there's nothing in it
mErrorMsg = "File or empty directory";
return false;
}
// Make a list of everything in it that we can get a thumbnail for
ArrayList<Entry> thumbs = new ArrayList<Entry>();
for (Entry ent: dirent.contents) {
if (ent.thumbExists) {
// Add it to the list of thumbs we can choose from
thumbs.add(ent);
}
}
if (mCanceled) {
return false;
}
if (thumbs.size() == 0) {
// No thumbs in that directory
mErrorMsg = "No pictures in that directory";
return false;
}
// Now pick a random one
int index = (int)(Math.random() * thumbs.size());
Entry ent = thumbs.get(index);
String path = ent.path;
mFileLen = ent.bytes;
String cachePath = mContext.getCacheDir().getAbsolutePath() + "/" + IMAGE_FILE_NAME;
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
// This downloads a smaller, thumbnail version of the file. The
// API to download the actual file is roughly the same.
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_960x640,
ThumbFormat.JPEG, null);
if (mCanceled) {
return false;
}
mDrawable = Drawable.createFromPath(cachePath);
// We must have a legitimate picture
return true;
} catch (DropboxUnlinkedException e) {
// The AuthSession wasn't properly authenticated or user unlinked.
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED) {
// won't happen since we don't pass in revision with metadata
} else if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE) {
// too many entries to return
} else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
// can't be thumbnailed
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
//mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
//mDialog.dismiss();
if (result) {
// Set the image now that we have it
mView.setImageDrawable(mDrawable);
} else {
// Couldn't download it, so show an error
showToast(mErrorMsg);
}
}
I am calling this from onCreate of my activity. My async task basically downloads some data from server. Main activity allows user to login to server and then I go for fetching the data. The problem that I am facing is that each AsyncTask creates its own thread. Also, none of those goes to completion.The thread status is always running. Is there a way to check that the new AsyncTask is only launched when the earlier is finished.
Following links can helps you, please have a look, Thanks.
Android: Can I chain Async task sequentially (starting one after the previous asynctask completes)
and
Android calling AsyncTask right after an another finished
Try this way
public ArrayBlockingQueue<Runnable> threadList = new ArrayBlockingQueue<Runnable>(
2000, true);
public ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0,
2000, 1000, TimeUnit.MILLISECONDS, threadList);
TimerTask t=new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//your code here
}
};
ThreadPool.execute(t);
The line timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms is responsible for the repetitive task.
As per the description of Timer class's schedule( TimerTaskObject, int start, int repete ) method , this will repeat a particular TimerTask for the defined time interval, i suggest you to change it as follows,
timer.schedule(doAsynchronousTask, 1000);//execute once after one second

Categories

Resources