This is my code:
package com.example.analogclock;
import android.view.View;
public class MyThread implements Runnable {
private View view;
public MyThread(View v){
view = v;
}
public void run() {
while(true){
try {
Thread.sleep(1000);
view.postInvalidate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Related
please help me guys..
my observablelist was updated successfully by background Thread.
but my GUI Update is not accurate.
addPiechart1 to HBOX
addPieChart2 to HBOX
observablelist1= getobservablelist from piechart1
observablelist2= getobservablelist from piechart2
pass observablelist1 to Thread
pass observablelist2 to Thread
ex
on the process i call
animatePie(observablelist1,value1);
animatePie(observablelist2,value2);
public void animatePie(ObservableList<PieChart.Data> obs,int[] value){
ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
#Override public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
pieAddToQueue add = new pieAddToQueue(obs,value);
//add.run();
executor.execute(add);
}
private class pieAddToQueue implements Runnable {
ObservableList<PieChart.Data> observableData;
int[] value;
int loop;
public pieAddToQueue(ObservableList<PieChart.Data> obs,int[] value){
observableData=obs;
this.value=value;
loop=0;
}
#Override
public void run() {
for(int i=0;i<value.length;i++){
observableData.get(i).setPieValue(value[i]);
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(MISInfoBoardBottom.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
You cannot update the UI on a background thread, so you must wrap the calls that change the UI with a Platform.runLater(...):
private class pieAddToQueue implements Runnable {
ObservableList<PieChart.Data> observableData;
int[] value;
int loop;
public pieAddToQueue(ObservableList<PieChart.Data> obs,int[] value){
observableData=obs;
this.value=value;
loop=0;
}
#Override
public void run() {
for(int i=0;i<value.length;i++){
PieChart.Data pieChartData = observableData.get(i);
int v = value[i] ;
Platform.runLater(() ->
pieChartData.setPieValue(v));
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(MISInfoBoardBottom.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I have this code which is an Activity that when started will check for internet connection, if there is a connection, then life goes on. Else a dialog appears to turn on the connection. However I made a thread that each 10 seconds will check for connection and in case the connection was lost it will display the dialog again.
package greensmartcampus.eu.smartcampususerfeedbackapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.net.InetAddress;
public class HomeScreen extends AbstractPortraitActivity {
private static final int WIFI_REQUEST_CODE = 1;
private boolean networkSettingsDialogOpened = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
this.runOnUiThread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
(...)
private boolean isInternetAvailable() {
try {
final InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
private void createNetErrorDialog() {
networkSettingsDialogOpened = true;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You need a network connection to use this application. Please turn on mobile network or Wi-Fi in Settings.")
.setTitle("Unable to connect")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivityForResult(i, WIFI_REQUEST_CODE);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
}
);
final AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == WIFI_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
networkSettingsDialogOpened = false;
Toast.makeText(HomeScreen.this, "Returned Ok",
Toast.LENGTH_LONG).show();
}
if (resultCode == RESULT_CANCELED) {
networkSettingsDialogOpened = false;
Toast.makeText(HomeScreen.this, "Returned Canceled",
Toast.LENGTH_LONG).show();
}
}
}
}
However I am getting the following error:
02-03 18:13:14.525 2683-2699/greensmartcampus.eu.smartcampususerfeedbackapp E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-193
Process: greensmartcampus.eu.smartcampususerfeedbackapp, PID: 2683
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.app.Dialog.<init>(Dialog.java:108)
at android.app.AlertDialog.<init>(AlertDialog.java:125)
at android.app.AlertDialog$Builder.create(AlertDialog.java:967)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen.createNetErrorDialog(HomeScreen.java:97)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen.access$200(HomeScreen.java:15)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen$1.run(HomeScreen.java:29)
Note: Line 97 is the one containing:
final AlertDialog alert = builder.create();
I googled alot, I am already using the cliche answer of runOnUiThread, but it doesn't fix it.
What am I missing?
The way you are checking the internet I guess you are causing your UI thread to sleep. You should do it like this.
Create one Handler and Thread running flag:
Handler mHandler = new Handler();
boolean isRunning = true;
Then, use this thread from your onCreate() method :
new Thread(new Runnable() {
#Override
public void run() {
while (isRunning) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
if(!HomeScreen.this.isInternetAvailable()){
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
}
}
});
} catch (Exception e) {
}
}
}
}).start();
Change this method slightly
private boolean isInternetAvailable() {
try {
final InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
isRunning = true;
return true;
}
} catch (Exception e) {
return false;
}
}
You can't call Thread.sleep() from code that is running on the UI thread. This is your code:
this.runOnUiThread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
You jest need to run the bit of code that shows the Dialog on the UI thread. Try this instead:
new Thread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
// Show the Dialog on the UI thread
HomeScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
HomeScreen.this.createNetErrorDialog();
}
});
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Is it possible to fire an event in a NamedBean asynchronously and to wait till all Consumers (Observers) are finished? The Consumer (Observers) should run asynchronously, but the event should be finished if all of them are finished.
e.g. I have 3 Beans (1 Bean which fires the event and 2 which observes the event).
Bean which fires the event:
#Named
#Stateless
public class TestExecuter implements Serializable {
#Inject
#MyEvent
private Event<QueryTO> myEvent;
public void run() {
QueryTO queryTO = new QueryTO(null, null);
FilterQualifier[] qualifiers = new FilterQualifier[3];
qualifiers[0] = new FilterQualifier(TestA.FILTER_ID);
qualifiers[1] = new FilterQualifier(TestB.FILTER_ID);
System.out.println("Fire event");
myEvent.select(qualifiers).fire(queryTO);
//wait till observers are finished
System.out.println("Event finished");
}
}
Bean 1 which observes
#Named
#Stateless
public class TestA implements Serializable {
public static final String FILTER_ID = "TestA";
public void generateFilterQueryEvent(
#Observes #Filter(FILTER_ID) #MyEvent QueryTO queryTo) {
System.out.println("TestA called");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("TestA finished");
}
}
Bean 2 which observes
#Named
#Stateless
public class TestB implements Serializable {
public static final String FILTER_ID = "TestB";
public void generateFilterQueryEvent(
#Observes #Filter(FILTER_ID) #MyEvent QueryTO queryTo) {
System.out.println("TestB called");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("TestB finished");
}
}
Expected result: Both beans execute the code at the same time and after 3 seconds the event is finished and the event is finished. Currently it executes TestA and after that TestB, so I have to wait 5 seconds.
AFAIK it's not supported by CDI although you can workaround it with an custom AsyncEvent class which gets the observers and calls them in separate threads. Here is a proof of concept example:
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.ObserverMethod;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
public class AsyncEvent<T> {
private static final AnnotationLiteral<Any> ANY =
new AnnotationLiteral<Any>() {
};
#Inject
private BeanManager beanManager;
private ExecutorService executorService;
public AsyncEvent() {
}
#PostConstruct
public void init() {
executorService = Executors.newFixedThreadPool(5);
}
#PreDestroy
public void shutdown() {
try {
executorService.shutdown();
final boolean terminated = executorService.awaitTermination(10, TimeUnit.SECONDS);
if (!terminated) {
throw new RuntimeException("awaitTermination timeout");
}
} catch (final InterruptedException ie) {
throw new RuntimeException(ie);
}
}
public void fire(final T event) {
fire(event, ANY);
}
public void fire(final T event, final Annotation... qualifiers) {
final Set<ObserverMethod<? super T>> observers = beanManager.resolveObserverMethods(event, qualifiers);
final Set<Callable<Void>> tasks = createCallablesForObservers(event, observers);
invokeAll(tasks);
}
private Set<Callable<Void>> createCallablesForObservers(final T event,
final Set<ObserverMethod<? super T>> observers) {
final Set<Callable<Void>> tasks = new HashSet<Callable<Void>>();
for (final ObserverMethod<? super T> observer: observers) {
final Callable<Void> callable = createCallable(event, observer);
tasks.add(callable);
}
return tasks;
}
private Callable<Void> createCallable(final T event,
final ObserverMethod<? super T> observer) {
final Callable<Void> callable = new Callable<Void>() {
#Override
public Void call() {
observer.notify(event);
return null;
}
};
return callable;
}
private void invokeAll(final Set<Callable<Void>> tasks) {
try {
executorService.invokeAll(tasks);
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Usage:
private static final AnnotationLiteral<Updated> UPDATED = new AnnotationLiteral<Updated>() {
};
#Inject
private AsyncEvent<Document> event;
public void run() {
System.out.println("Fire event");
final Document document = new Document("test event");
event.fire(document);
event.fire(document, UPDATED);
...
}
Good Evening to everybody!
i have the following trouble: i'm tryin to measure the decibels(of the voice) using the microphone of my mobile phone but dont know why it doesn´t work!!! any suggestions??thanks for help!!
The program is this:
`package com.dani;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class Pruebita2 extends Activity {
TextView TextView;
StringBuilder builder=new StringBuilder();
MediaRecorder mRecorder;
double powerDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pruebita2);
TextView=new TextView(this);
setContentView(TextView);
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRecorder.start();
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
powerDb = 20 * log10(getAmplitude() / referenceAmp);//obtain the DECIBELS
}`
this code works for me:
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class Noise extends Activity {
TextView mStatusView;
MediaRecorder mRecorder;
Thread runner;
private static double mEMA = 0.0;
static final private double EMA_FILTER = 0.6;
final Runnable updater = new Runnable(){
public void run(){
updateTv();
};
};
final Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noiselevel);
mStatusView = (TextView) findViewById(R.id.status);
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
try
{
Thread.sleep(1000);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
public void onResume()
{
super.onResume();
startRecorder();
}
public void onPause()
{
super.onPause();
stopRecorder();
}
public void startRecorder(){
if (mRecorder == null)
{
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try
{
mRecorder.prepare();
}catch (java.io.IOException ioe) {
android.util.Log.e("[Monkey]", "IOException: " +
android.util.Log.getStackTraceString(ioe));
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
try
{
mRecorder.start();
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
//mEMA = 0.0;
}
}
public void stopRecorder() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public void updateTv(){
mStatusView.setText(Double.toString((getAmplitudeEMA())) + " dB");
}
public double soundDb(double ampl){
return 20 * Math.log10(getAmplitudeEMA() / ampl);
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
}
I want to create a MIDlet which automatically starts using push registry function
PushRegistry.RegisterConnection("sms://:50000", this.getclass().getname(),"*");
Following is the code which I have come up with, and cannot find the problem with it as it is not responding in any way to any message.
P.S. I am aware of the fact that dynamic registration requires me to first run the app once.
public class Midlet extends MIDlet implements CommandListener,Runnable {
private Display disp;
Form form = new Form("Welcome");
Command ok,exit;
public void startApp() {
String conn[];
exit= new Command("exit",Command.CANCEL,2);
ok= new Command("ok",Command.OK,2);
form.addCommand(ok);
form.addCommand(exit);
form.setCommandListener(this);
conn = PushRegistry.listConnections(true);
disp=Display.getDisplay(this);
disp.setCurrent(form);
form.append("Midlet");
form.append("Press OK to register sms connection");
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if(c.getLabel().equals("exit"))
{
System.out.println("exit pressed");
destroyApp(true);
}
if(c.getLabel().equals("ok"))
{
String[] cn;
cn=PushRegistry.listConnections(true);
form.append(""+cn.length);
for(int i=0;i<cn.length;i++)
{
form.append(cn[i]);
}
Thread t = new Thread(this);
t.start();
}
}
public void run() {
try {
PushRegistry.registerConnection("sms://:50000",this.getclass().getname, "*");
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
Your code worked when I replaced this line PushRegistry.registerConnection("sms://:50000",this.getclass().getname, "*");
with PushRegistry.registerConnection("sms://:50000",<actual name of the class>, "*");