I am very confused as to why I cannot get this to work. I want to have a screen with no buttons run for 5 seconds while I do some things in the background, then navigate back to another screen. Is this not possible?
I have tried to put the code to run the background items in onCreate, onStart, and onResume, and all of these methods are fired before the screen actually displays. Is there another way to do this?
Edit The most recent version of my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
}
protected void onResume(){
super.onResume();
commitSync();
}
private void commitSync(){
TextView monthDayYear = (TextView)findViewById(R.id.month_day_year);
TextView hourMinuteSecond = (TextView)findViewById(R.id.hour_minute_second);
_application = (App)getApplicationContext();
try {
CountDownLatch latch = new CountDownLatch(1);
latch.await(5, TimeUnit.SECONDS);
//Ensure that we have flash
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
Camera androidCamera = Camera.open();
Camera.Parameters p = androidCamera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
androidCamera.setParameters(p);
//Flash and then turn off
androidCamera.startPreview();
latch.await(50, TimeUnit.MILLISECONDS);
androidCamera.stopPreview();
//Flash screen white
//Get date and time
Module syncModule = _application.getModule();
syncModule.start();
Calendar syncTime = syncModule.getDateAndTime();
//http://stackoverflow.com/questions/21988004/get-time-in-hhmmss-from-seconds-in-java
monthDayYear.setText(new SimpleDateFormat("MM/dd/yyyy").format(syncTime.getTime()));
hourMinuteSecond.setText(new SimpleDateFormat("HH:mm:ss:00").format(syncTime.getTime()));
//Navigate back to MainActivity
Intent mainActivityIntent = new Intent(SyncActivity.this, MainActivity.class);
startActivityForResult(mainActivityIntent, 1);
} else {
throw new Exception("Cannot access Android Flash");
}
} catch (Exception ex) {
Util.appendLog("Exception occured in Sync: " + ex.getMessage());
}
}
Maybe this help you:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// Do some work like:
finish();
}
}, 500);
This run a code after some delay and you can put this code in your desired screen.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//The code you want to execute
}
}, timeUntilExecution);
This code should execute that run() method after the timeUntilExecution variable (in milliseconds) you could use this to execute what you want to do after the delay. Hope this helps.
Related
I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}
I have a problem with my game - when the live is 0 it should show the game-over screen and finish the game-activity, but the screen freezes instead.
The code in the surface is:
if(live <= 0){
try {
gameThread.setGameRunning(false);
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
gameOverHandler.post(new Runnable() {
#Override
public void run() {
gameOver.onGameOver(score);
}
});
}
And the Interface in the GameActivity:
#Override
public void onGameOver(int score) {
Intent gameOver = new Intent(this, GameOver.class);
gameOver.putExtra("score", score);
startActivity(gameOver);
gameEngine.stop();
this.finish();
}
The Game-thread loops the canvas drawing and the Engine the movements of the Characters.
I hope you can help me.
Thanks!
You must have initialised gameOverHandler somewhere in the code using
gameOverHandler = new Handler();
or
gameOverHandler = new GameOverHandler();
Try replacing it with
gameOverHandler = new Handler(Looper.getMainLooper());
or
gameOverHandler = new GameOverHandler(Looper.getMainLooper());
depending on what class you have actually used.
Sry my internet was down about the weekend i've solved it with the constructor
public GameSurface(Context context, OnGameOver onGameOver){
...
}
and in the MainActivity
gameSurface = new GameSurface(this, this);
and implementing OnGameOver
a litte bit rewrite for my code but its works...
I want to wirte an android app that will read input from user each time i press abutton and will handle it in different thread(not activity) also i dont want to open new thread each time i need an example for that.
Thanks a lot!
Get the text from user input field:
EditText editText = findViewById(R.id.yourEditTextId);
final String text = editText.getText().toString;
Then you could do something like this:
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// do something with String text
}
};
handler.post(r);
Or this:
new Thread(new Runnable() {
public void run() {
// do something with String text
}
}).start();
You can find info about threads in Android here: http://developer.android.com/guide/components/processes-and-threads.html
you could use this link here
`Thread thread = new Thread()
{
#Override
public void run() {
try {
// do something here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();`
I want to write a download manager app, in the activity I add a progress bar which show the current progress to the user, now if user touch the back button and re-open the activity again this ProgressBar won't be updated.
To avoid from this problem I create a single thread with unique name for each download that keep progress runnable and check if that thread is running in onResume function, if it is then clone it to the current thread and re-run the new thread again but it won't update my UI either, Any ideas !?
#Override
public void onResume()
{
super.onResume();
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (int i = 0; i < threadArray.length; i++)
if (threadArray[i].getName().equals(APPLICATION_ID))
{
mBackground = new Thread(threadArray[i]);
mBackground.start();
downloadProgressBar.setVisibility(View.VISIBLE);
Toast.makeText(showcaseActivity.this
, "Find that thread - okay", Toast.LENGTH_LONG).show();
}
}
private void updateProgressBar()
{
Runnable runnable = new updateProgress();
mBackground = new Thread(runnable);
mBackground.setName(APPLICATION_ID);
mBackground.start();
}
private class updateProgress implements Runnable
{
public void run()
{
while (Thread.currentThread() == mBackground)
try
{
Thread.sleep(1000);
Message setMessage = new Message();
setMessage.what = mDownloadReceiver.getProgressPercentage();
mHandler.sendMessage(setMessage);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch (Exception e)
{/* Do Nothing */}
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message getMessage)
{
downloadProgressBar.setIndeterminate(false);
downloadProgressBar.setProgress(getMessage.what);
if (getMessage.what == 100)
downloadProgressBar.setVisibility(View.GONE);
}
};
Download button code:
downloadBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
downloadProgressBar.setVisibility(View.VISIBLE);
downloadProgressBar.setIndeterminate(true);
downloadProgressBar.setMax(100);
Intent intent = new Intent(showcaseActivity.this, downloadManagers.class);
intent.putExtra("url", "http://test.com/t.zip");
intent.putExtra("receiver", mDownloadReceiver);
startService(intent);
updateProgressBar();
}
});
I'd strongly recommend reading the Android Developer blog post on Painless Threading. As it states, the easiest way to update your UI from another thread is using Activity.runOnUiThread.
I have implemeted a custom camera and I want it to go, after a period of time into a standby state. The standby concsists from a stopPreview, a camera release and a view that tells the user to tap in order to exit the standby. Because I set the text within the new thread, I get the CalledFromWrongThreadException, but I don't know what the solution could be. I found other posts around, but none of them really worked.
Code:
private void initCamera()
{//more code
threadModifiedText = (TextView) findViewById(R.id.textView1);
Thread standbyThread = new Thread()
{
#Override
public void run()
{
try
{
while (timeCounter > 0)
{
if (!activeThread)
{
sleep(100);
if (timeCounter % 10 == 0)
{
threadHandler.sendEmptyMessage((int) timeCounter / 10);
}
timeCounter--;
}
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.stopPreview();
mCamera.release();
TextView standbytext = new TextView(SlicesActivity.this);
standbytext.setText("Tap to exit standby mode");
FrameLayout preview = (FrameLayout) findViewById(id.FrameLayout_camera_preview);
preview.addView(standbytext);
}
};
standbyThread.start();
//more code}
And
#Override
public void onUserInteraction()
{
Log.d("~~~~~~~~~", "apasat");
activeThread = true;
timerCounter = 300;
}
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
// whenever the Thread notifies this handler we have
// only this behavior
threadModifiedText.setText("\ncounter is " + Integer.toString(msg.what));
}
};
Please guys, give me some suggestions. 10x
try to use
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO: update your UI here
}
});
in your thread to update UI
You cannot set text values inside any thread except the UI thread. Complete your background thread operations and set the text value after your operations are over in the UI thread.