starting android activity from a thread's inside thread. - java

This code is inside MainActivity class.
Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), NextActivity.class);
startActivity(i);
}
});
thread2.start();
}
});
thread1.start();
When i run this code nothing happend.

startActivity should be run in the main thread, so if you need to run it from your thread2, I'd post it to run in the main thread.
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
Intent i = new Intent(context, NextActivity.class);
startActivity(i);
}
mainHandler.post(myRunnable);
};

You cannot use other threads to work on UI or calling other activities,
You can do it from main UI thread only.
Intent i = new Intent(getApplicationContext(), NextActivity.class);
startActivity(i);
Running other threads means, you are doing some extra tasks simultaneously along with the main thread.

Related

How to gracefully shut down all activities and close all running threads in an Android app?

At the moment, in each one of my activities I have this method:
private void registerReceiverClose(){
Activity activity = this;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLOSE_ALL");
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
activity.finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
and this one as well:
#Override
protected void onDestroy() {
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
They're triggered by the following logout button:
Button logout = findViewById(R.id.logout_button);
logout.setOnClickListener(click -> {
Intent intent = new Intent("CLOSE_ALL");
this.sendBroadcast(intent);
});
One thing that I'm sure is not closing in the right way, is that I have this code:
private static final ScheduledExecutorService pollingScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
private static final Object lock = new Object();
private static ScheduledFuture<?> currentRunningTask;
public void longPoll() {
synchronized (lock) {
if (currentRunningTask != null) {
currentRunningTask.cancel(true);
}
try {
currentRunningTask = pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
}
}
public void request() {
Thread requestThread = new Thread(this);
requestThread.start();
}
which continues to issue requests even after I think I should be logged out, which causes errors on the server.
How can I make sure all the threads stop gracefully and the application closes down in the right way?
You could wrapthe polling code inside of a Service. This service can then be stopped using
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
Inside of the service, you can override onDestroy() to clean resources up.

In which Thread is an Activity called from inside a Runnable?

If I start a new thread by calling the start() method, and then start a new Activity from its run method, is my next activity and all the followups activities considered to be in my new Thread?
Thread test = new Thread(new Runnable() {
#Override
public void run() {
Intent n = new Intent(this, SecActivity.class);
startActivity(n);
}
});
test.start();

Android-Starting new Activity in Handler/runnable is really slow

I am making an android app that requires a runnable. I am starting a new activity from the runnable. The new activity comes up and works fine. The issue is that when the call is made to start the activity, it is incredibly slow. It takes a full 5 seconds to start the activity when I want it to be instantaneous.
Boolean handlerrun=true;
Intent intent= new Intent(this,newactivity.class);
int somevalue=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameactivity);
handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
if(handlerrun){somevalue++;}
if(somevalue>500){
handlerrun=false;
startActivity(intent);
finish();
}
handler.postDelayed(this, 1);}
}
};
handler.postDelayed(r, 1);
}
The activity starts when somevalue is greater than 500. To stop the handler from increasing the value of somevalue, I use a boolean handlerrun, which only runs the handler when it is true. When somevalue is greater than 500, handlerrun= false so the handler doesn't increase the value. I tried using the handler.removeCallbacksandMessages() method but it didn't work. Logcat doesn't give me any errors.Any help would be appreciated.
You could try something like this:
#Override
protected void onResume() {
super.onResume();
if(done){
return;
}
done = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), YourActivity.class));
finish();
overridePendingTransition(0, 0);
}
}, 5000);
}
That will start YourActivity after 5 seconds approximately.
Hope it helps.

why i cannot send android intent from within new thread?

private void Foo() {
// progressDialog = ProgressDialog.show(this, "", "Loading...");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(this, TodoDetailActivity.class);
i.putExtra("driveUri", file.getAlternateLink());
startActivityForResult(i, SAVE);
}
});
t.start();
}
I get this error:
The constructor Intent(new Runnable(){}, Class<TodoDetailActivity>) is undefined
I have tried to change to explicit declaration, but it didn't help
android.content.Intent i = new android.content.Intent.Intent(this, TodoDetailActivity.class);
though I know there is such a signature from past use.
This line
Intent i = new Intent(this, TodoDetailActivity.class);
Is inside the Anonymous Class Runnable.
Change it to
Intent i = new Intent(getBaseContext(), TodoDetailActivity.class);
Try to change
Intent i = new Intent(this, TodoDetailActivity.class); in
Intent i = new Intent(getActivity(), TodoDetailActivity.class); if you are in a Fragment, or
by
Intent i = new Intent(yourActualActivity.this, TodoDetailActivity.class); if you are in an Activity
Intent need context (of some activity of application), but in thread this (in new Intent(this, TodoDetailActivity.class);) passes the context of you thread, which is not an activity.
so just getApplicationContext() or context of activity form which thread is started like MainActivity.this
You are using Itennt() inside the Thread, so this means thread's object, which is wrong for Intent's syntax.
You should modify your code as follows,
private void Foo()
{
// progressDialog = ProgressDialog.show(this, "", "Loading...");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), TodoDetailActivity.class);
i.putExtra("driveUri", file.getAlternateLink());
startActivityForResult(i, SAVE);
}
});
t.start();
}

Wait for a thread before continue on Android

I've one thread, but i'd like to wait for it to finish before continue with the next actions. How could i do it?
new Thread(
new Runnable() {
#Override
public void run() {
mensaje = getFilesFromUrl(value);
}
}).start();
here i'd like to put something (but loops) that knows when thread finishes and evaluate the result (mensaje)
btnOk.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
lblEstado.setText(mensaje);
if(mensaje.equals("Importado"))
startActivity(new Intent(ScanUrl.this, MainActivity.class));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
mensaje = getFilesFromUrl(value);
}});
t.start(); // spawn thread
t.join(); // wait for thread to finish

Categories

Resources