How can i correct strobe effect - java

I want to create a strobe effect,make the flashlight blink.Below is my code,right now what i have achieve is to make it flash but only once,that's why i need to help me make it flash for a great deal of time.
public class Strobe extends Activity {
Camera cam;
private static final String TAG = null;
private Handler mHander = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
strobe();
}
private void turnOnLight(){
for(int x = 0; x == 10; x++);{ //although for does exist does nothing and that is in all for i have put around my program,don't know why
Log.d("tagname","runs 10 times a");
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(params);
cam.startPreview();
cam.autoFocus(new AutoFocusCallback(){
public void onAutoFocus(boolean success, Camera camera) {
}
});
}
}
private void turnOffLight(){
for(int x = 0; x == 10; x++);{
cam.stopPreview();
cam.release();
Log.d("tagname","runs 10 times b");
}
}
private void strobe(){
for(int x = 0; x == 10; x++);{
Thread timer = new Thread(){
public void run(){
turnOnLight();
try{
Thread.sleep(300);
}catch(InterruptedException e){
e.printStackTrace();
}
turnOffLight();
Log.d("tagname","runs 10 times c");
};
};timer.start();
};
}
};

int n=10000;
while(n-->0)
{
int n=100000;
while(n-->0)
{
turnOnLight();
try{
Thread.sleep(300);
}catch(InterruptedException e)
{
e.printStackTrace();`enter code here`
}
turnOffLight();
Log.d("tagname","runs 10 times c");
}
}

Have you considered the fact that the syntax for your for loops is all wrong? For staryers, you are using == where you probably want to use <, and you put a semicolon after the for statement where there shouldn't be one. Review the proper syntax for a for loop and try to rewrite your code.

Related

Implement a time delay in android application

Below is a peice of code where on click the player will make their move by placing the X counter and then the computer will make their move by placing a O counter. The
only issue with this code currently is that when the player places their X counter, the O counter is placed as well at the same time. So it looks like both the player
and the computer has made their moves at the same time and that happens everytime the player makes their move.
What I want to ask, is it possible to include like a 2 second time delay so that the player will place their X and then after 2 seconds the computer will place their O?
Thanks in advance
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
computerMove();
}
}
private void computerMove() {
String[][] field = new String[3][3];
Random random = new Random(); //you may want to declare this as a class field
List<Button> emptyButtons = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.add(buttons[i][j]);
}
}
}
Button selectButton;
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][2].equals("")){
//prevent win/win on rows by selecting the correct button here
}
else if (field[i][0].equals(field[i][2])
&& field[i][1].equals("")){
//prevent win/win on rows by selecting the correct button here
}
else if (field[i][1].equals(field[i][2])
&& field[i][0].equals("")){
//prevent win/win on rows by selecting the correct button here
}
else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
}
You could put computer logic inside handler or timer task: How to call a method after a delay in Android
but you also need some flag, that will block user placing X while you are waiting for computer to make it move.
i edited your onclick with the delay and i think you gonna need some sort of the flag wich blocks user until computer makes the move !
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
//2000 is your delay in mills format
v.postDelayed(new Runnable() {
#Override
public void run() {
computerMove();
}
},2000)
}
}
and i think it would be good idea to use some random number between 1sec to 3sec for delay and not the constant delay it creates better experience for user
You can check out the Handler and Runnable class in android. You can delayed the time of a method as required.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
}
}, 100);

Needing JAVA help in animation

I'm new in Java (still learning) all the other works have gone well but only this animation gives my headache and the coffee won't even help=(!
I should make an animation of Javaman (10 gif pictures named as T1, T2,...T10) I should use Thread, MediaTracker-class and addImage-method. Then I should specify the speed of the animation by using sleep-method (I used join-method if that's right??).
(MY JAVA CODE GOES LIKE THIS)
import java.applet.Applet;
import java.awt.*;
public class Animaatio extends Applet implements Runnable {
Image[] images = null;
MediaTracker tracker = null;
int current = 0;
Thread animThread;
#Override
public void init() {
// Creating a new media tracker, to track loading images
tracker = new MediaTracker(this);
// Creating an array of ten images
images = new Image[10];
// Downloading the images
for (int i = 0; i < 10; i++) {
// Loading the images
images[i] = getImage(getCodeBase(), (i + 1) + "T.gif");
tracker.addImage(images[i], 0);
}
try {
tracker.waitForAll();
} catch (InterruptedException e) {
}
}
#Override
public void start() {
if (animThread == null) {
animThread = new Thread(this);
animThread.start();
}
try {
animThread.join();
} catch (InterruptedException e) {
}
}
#Override
public void paint(Graphics g) {
g.drawImage(images[current++], 0, 0, this);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
}
}
The problem is that I don't see any animation just an empty applet viewer which just keeps running. Problem might be caused if the images are storaged in the wrong place? If someone could wreally help me, I would be really thankful for my knight=).

Real-time update of MPAndroidChart graph from bluetooth data

I am trying to plot data received from Bluetooth with real-time with MPAndroidChart library. I believe there is problem with thread deadlocks but I cannot figure it out exactly.
Here is how the code goes:
After connection is established, when "Read" button is pressed.
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent;
if (dtToggle.onOptionsItemSelected(item)) { return true; }
switch (item.getItemId())
{ ......
case R.id.menu_read:
String message;
if (oper_state) {
oper_state = false;
put_thread = new PutTask();
put_thread.start();
timer = new Timer();
timer.schedule(new MyTask(),10, 100);
//feedMultiple();
//put_thread.start();
message = CMD_READ + "";
sendMessage(message);
} else {
if(timer != null)
{
message = CMD_STOP + "";
sendMessage(message);
put_thread.interrupt();
timer.cancel();
timer.purge();
timer = null;
oper_state = true;
//put_thread.interrupt();
try{
if(fos != null)
fos.close();
}
catch(Exception e)
{
}
}
}
return true;
PutThread is where I add received data from bluetooth to data queue:
class PutTask extends Thread {
public void run(){
int channel_idx;
customParsePackets mBluetoothService;
while(true)
{
mBluetoothService = mChestPatchService;
for(int i=0;i<num_siganl_list;i++)
{
if(!mBluetoothService.isEmpty(i))
{
int read_data = mBluetoothService.poll_data(i);
put_data(i, read_data);
sample_incr(i);
}
}
}
}
}
Put_data function:
public synchronized void put_data(int i, int int_data)
{
int tmp_sample = 0;
int tmp_data, filtered_data;
double tmp_diff_val=0;
tmp_sample = sample_get_value(i);
tmp_data = int_data;
if(mECGSignCheck.isChecked())
tmp_data = -tmp_data;
if(mFilterCheck.isChecked() == true)
ecg_data[i] = ECG_bpf[i].getOutputSample(tmp_data);
else
ecg_data[i] = tmp_data;
if(i==1) {
tmp_diff_val = mRpeak.put_ecg(tmp_sample, tmp_data);
peak_point = mRpeak.Apply_ecg();
Log.d("PEAK", "Data pushed" );
}
synchronized (chartQueue_Lock){
if(tmp_sample % 4 == 0)
**chartQueue[i].offer(new Point(tmp_sample, (int)ecg_data[i]));**
}
}
And this is where I update my UI:
class MyTask extends TimerTask {
public void run(){
runOnUiThread(new Runnable(){
#Override
public void run(){
//updateui();
dataseries_add_new((int)(Math.random() * 7),0, Math.random() * 500);
}
});
}
}
The above code works perfectly fine for GraphView Library. But I want to implement it for MPAndroidChart.
For MPAndroidChart when I start do dataseries_add_new((int)(Math.random() * 7),0, Math.random() * 500); in the above class it works well. But my goal is to add the data from the data queue to the graphs. So in order to do so, in the above code sample instead of dataseries_add_new((int)(Math.random() * 7),0, Math.random() * 500); I call updateui() from where I poll the data from the queue and call dataseries_add_new((int)(Math.random() * 7),0, Math.random() * 500);:
public void updateui()
{
long starttime, endtime;
int tmp_sample = sample_get_value(APW_SIGNAL);
Point qPoint = new Point();
for(int i=0; i<num_siganl_list; i++)
{
int poll_num = 0;
while(!chartQueue[i].isEmpty())
{
if(poll_num != 0)
{
if(qPoint.x % 4 == 0) {
dataseries_add_new(i, qPoint.x, qPoint.y);
}
}
synchronized (chartQueue_Lock)
{
qPoint = chartQueue[i].poll();
}
poll_num = 1;
}
Where the graph update code is taken from MPAndroidChart sample app for Realtime Chart.
When "Read" button is presed app screen goes black for some time and then gives an error. Could you please provide some insight about how to solve the problem?

Java async problems

So my code works just the way I want it the only issue I'm having is this.. Basically I am having a main class which controls gates on a railroad track, when a train is approaching or crossing the track from either 1 of two tracks the gates should close. The only issue I'm having is the statements for when a gate opens or closes spam like 3-5 times everytime it does something so if the gate is closing it will go..
GATE: Closing
GATE: Closing
GATE: Closing
GATE: Closing
GATE: Closing
GATE: Closed
I'm wondering why this is occuring, here is my code for the Gate class and Main class
public class Gate {
private boolean isClosed = false;
private boolean closing = false;
private boolean opening = false;
public Gate(){
}
public void close(){
if(!(isClosing() == true)){
Runnable task = new Runnable() {
public void run() {
try {
setClosing(true);
setOpening(false);
System.out.println("GATE: Closing");
Thread.sleep(400);
System.out.println("GATE: Closed");
setClosed(true);
setClosing(false);
}catch(Exception ex){
}
}
};
new Thread(task, "closeThread").start();
}
}
public void open(){
if(!(isOpening() == true)){
Runnable task = new Runnable() {
public void run() {
try {
setOpening(true);
System.out.println("GATE: Opening");
Thread.sleep(400);
setOpening(false);
if(closing == false){
setClosed(false);
System.out.println("GATE: Opened");
}
}catch(Exception ex){
}
}
};
new Thread(task, "openThread").start();
}
}
public boolean isClosed(){
return isClosed;
}
public boolean isClosing(){
return closing;
}
public boolean isOpening(){
return opening;
}
public synchronized void setClosing(boolean t){
closing = t;
}
public synchronized void setOpening(boolean t){
opening = t;
}
public synchronized void setClosed(boolean t){
isClosed = t;
}
}
public class Controller {
public static void main(String[] args){
Track t1 = new Track("Track 1");
Track t2 = new Track("Track 2");
Gate g = new Gate();
t1.simulateTrack();
t2.simulateTrack();
do{
System.out.print("");
if((t1.isApproaching() || t1.isCrossing()) || (t2.isApproaching() || t2.isCrossing())){
if(!g.isClosed() && !g.isClosing()){
g.close();
}
}else if(g.isClosed() && !g.isOpening()){
g.open();
}
}while((t1.isSimulating() || t2.isSimulating()));
}
}
Also the code for Track
import java.security.SecureRandom;
public class Track {
private static final SecureRandom gen = new SecureRandom() ;
private boolean approaching = false;
private boolean atCrossing = false;
private boolean simulating = false;
private String trackName = "";
public Track(String n){
trackName = n;
}
public void simulateTrack(){
Runnable task = new Runnable() {
public void run() {
try {
setSimulating(true);
for(int i = 0; i < 10; i++){
Thread.sleep((gen.nextInt(5000) + 2500));
setApproaching(true);
System.out.println(trackName + ": Train is now approaching.");
Thread.sleep((gen.nextInt(5000) + 3500));
setCrossing(true);
setApproaching(false);
System.out.println(trackName + ": Train is now crossing.");
Thread.sleep((gen.nextInt(1000) + 1000));
setCrossing(false);
System.out.println(trackName + ": Train has left.");
}
setSimulating(false);
} catch (Exception ex) {
}
}
};
new Thread(task, "simulationThread").start();
}
public boolean isApproaching(){
return approaching;
}
public boolean isCrossing(){
return atCrossing;
}
public boolean isSimulating(){
return simulating;
}
public synchronized void setSimulating(boolean t){
simulating = t;
}
public synchronized void setApproaching(boolean t){
approaching = t;
}
public synchronized void setCrossing(boolean t){
atCrossing = t;
}
}
This is just an idea:
By shooting the close() logic on a background thread you lose the atomicity. The main's do loop can go around 5 times before it gives up the control of the main thread and one of the "closeThread"s start executing. Don't you see multiple "GATE: Closed"s as well?
Try this (not tested, sorry):
public synchronized void close() { // added synchornized
if (!isClosing()) { // read: "if not closing"
setClosing(true); // set closing so next time close() is called it is a no op
setOpening(false); // close other loopholes so the state is correct
System.out.println("GATE: Closing");
// we're in closing state now, because the close method is almost finished
// start the actual closing sequence
Runnable task = new Runnable() {
public void run() {
try {
Thread.sleep(400);
System.out.println("GATE: Closed");
setClosed(true);
setClosing(false);
}catch(Exception ex){
}
}
};
new Thread(task, "closeThread").start();
}
}
You'll need to modify open() the same way, so that the invariants are always kept. Checking and setting the closing and opening flags are mutually exclusive, that's what you get by placing synchronized on both of them.

How can I make Java add to a private int mouseClicks every second?

public class Blank extends WindowController
{
private int mouseClicks;
public void onMousePress(Location point)
{
mouseClicks++;
}
}
My goal is for if mouseClicks to increment once every second, while while only having to click once to start it.
Here is the best solution I can get.
public class Blank extends WindowController
{
private final AtomicInteger mouseClicks = new AtomicInteger();
private boolean hasStarted = false;
public void onMousePress(Location point)
{
if(!hasStarted){
hasStarted = true;
Thread t = new Thread(){
public void run(){
while(true){
mouseClicks.incrementAndGet(); //adds one to integer
Thread.sleep(1000); //surround with try and catch
}
}
};
t.start();
}
}
}
Look into using Thread.sleep(1000); to pause execution for one second.
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
You could test the time passed since the last click.
long lLastClickTime = Long.MIN_VALUE;
public void onMousePress(Location point) {
final long lCurrentTime = System.currentTimeMillis();
if(lCurrentTime - lClickLastTime >= 1000) {
mouseClicks++;
lLastClickTime = lCurrentTime;
}
}

Categories