Java android eclipse, starting activity in thread: application stopped working - java

Hey I am doing a simple Android app and I am trying to a start new activity from a thread like this:
public void startUI (){
Thread t = new Thread(){
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent goToMenu = new Intent(getApplicationContext(), MainMenu.class);
startActivity(goToMenu);
}
});
;}
};
t.start;
}
But when my code comes to this line
Intent goToMenu = new Intent(getApplicationContext(), MainMenu.class);
It crashes and writes: "application stopped working".

If you want to start an activity you need to use Activity context as a first parameter. If you use Application context then your MainMenu activity must have a FLAG_ACTIVITY_NEW_TASK flag set. You cannot start new activity in the same task from application context.
Refer: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NEW_TASK
As #Raghunandan mentioned, if you want a delay, you should use a Handler like this:
uiHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent goToMenu = new Intent(getApplicationContext(), MainMenu.class);
goToMenu.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(goToMenu);
}
}, 500);

Related

Android Studio on click button after a splash screen and a main screen [duplicate]

I have an application in which I'm receiving a sms containing his location.On receiving sms it calls another activity to start and passes that location to that activity to plot it on the map.Before calling the second activity it shows a toast like notification on the screen but somehoe due to calling second activity that toast doesn't come up.My question is how can we delay the calling of second activity from this activity ?
You can use something like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(SearxhJobs.this,JobsTypes.class);
startActivity(i);
}
}, 5000);
Here it waits upto 5 seconds to launch activity.
Hope it helps
You can do it with a Handler like this
Handler h = new Handler(){
#Override
public void handleMessage(Message msg) {
Intent i = new Intent().setClass(ctx, MainActivity.class);
startActivity(i);
}
};
h.sendEmptyMessageDelayed(0, 1500); // 1500 is time in miliseconds
Make an AsyncClass that does Thread.sleep() in the doInBackground() method, then navigate to your new activity in the your onPostExecute() method.
Call your toast message and then execute the AsyncClass.
For Kotlin
Handler().postDelayed({
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}, 5000)
Try:
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment then use getActivity() as the context.
startActivity(new Intent(SplashActivity.this, MainActivity.class));
// To close the CurrentActitity, r.g. SpalshActivity
finish();
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Simply set the layout!
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.next); //where <next> is you target activity :)
}
}, 5000);
An example would be the following:
Handler TimeDelay=new Handler();
if(previous=="geofence"){
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
Runnable r = new Runnable() {
#Override
public void run() {
/*
Intent intent = new Intent(
MyBroadcastMessageReceiver.class.getName());
intent.putExtra("some additional data", choice);
someActivity.sendBroadcast(intent);*/
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
}
};
TimeDelay.postDelayed(r, 150000);

Activity whith pitch detect TarsosDSP no restart

I wrote a guitar tuner in music application. The main activity launch the tuner when click on button. The tuner works fine. But if I come back to main activity.
The Tuner activity start, but pitch detection does not.
The thread don't stop for the recorder.
I launch an activity Act_Accordage from the main activity with
public void clicAccordage(View v){
Intent intentAct_Accordage = new Intent(this, Act_Accordeur .class);
startActivity(intentAct_Accordage);
}
Here is my Act_Accordage activity
public final AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 2048, 0);
....
dispatcher.addAudioProcessor(new PitchProcessor(PitchEstimationAlgorithm.YIN, 22050, 2048, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult,
AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
if (Logo.interrupted()) {
return;
}
if (pitchInHz > -1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// display name note and cursor ou UI thread
textFreqNote.setText(String.valueOf(pitchInHz) + " CREATE ");
Affcurseur(pitchInHz);
});
}
}
}));
new Thread(dispatcher, "Audio Dispatcher");
2***/I come back main with button or backbutton
public void onclicSetBackMain(View v) {
Act_Accordeur.this.finish();
Toast.makeText(Act_Accordeur.this, "Guitare accordée", Toast.LENGTH_LONG).show();}
Use dispatcher.stop(); to stop the Audio Dispatcher thread.It took me a long time in the official documentation but it was worth it.

Android: Redirect to another Activity after delay

So I am developing a simple app for a college project, And I have been able to integrate a Facebook login using fragments.
But I now am stuck trying to redirect the user after they login. I simply want to redirect them to the second activity page
Here is my code for the Facebook login success
private FacebookCallback<LoginResult> mCallback=new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
display.setText("Welcome: " + profile.getFirstName());
//Redirect to Second Activity
}
}
To make a delayed transition use Handler class's postDelayed(Runnable r, long delayMillis) method, for example:
Java
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment
// then use getActivity() as the context.
startActivity(new Intent(CurrentActivity.this, TargetActivity.class));
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Kotlin with Anko
val someThread = Runnable {
startActivity(intentFor<TargetActivity>())
}
Handler().postDelayed(someThread, 1500)
Simply call a new activity through intent:
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(i);
finish();
Check this:-
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(CurrentActivity.this,Next.class);
startActivity(i);
}
}, 3000);
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. Each Handler instance is
associated with a single thread and that thread's message queue. When
you create a new Handler, it is bound to the thread / message queue of
the thread that is creating it -- from that point on, it will deliver
messages and runnables to that message queue and execute them as they
come out of the message queue.
You can use Handler postDelayed Method easily .
Handler hd = new Handler();
hd.postDelayed(new Runnable() {
#Override
public void run() {
// Add Your Intent
}
}, 2000); // Time Delay ,2 Seconds
}
In Kotlin;
val r = Runnable {
startActivity(Intent(this, AuthorActivity::class.java))
}
val h = Handler()
h.postDelayed(r, 10)

Stop/Pause/Sleep Service if connection unavailable and resume if available

I have an application in which I have created a service MyService.class
Now MyService.class is tied to my activity using bindService() but I want my service to run in the background even if activity destroys itself.
So I started the service and then bind it like below:
private void doBindService() {
if (!isServiceBound){
Log.d(LOG_TAG, "Binding Service...");
if (mBtAdapter != null && mBtAdapter.isEnabled()){
Intent intent = new Intent(MyActivity.this, MyService.class);
startService(intent);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
}
}
In MyActivity's onDestroy method I am unbinding the service
Now my service is running smoothly until the connection with the remote device breaks. I want to pause/sleep/stop this service if connection breaks, then after every 60 seconds it tries to start the service/connection.
I have tried this but doesn't work.
private void stopService() {
doUnbindService();
stopService(new Intent(MyActivity.this, MyService.class));
startService(new Intent(MyActivity.this, MyService.class));
}
Please any help will be much appreciated. Thanks in advance!!!
Try this
create a method that perform the Operation you want
create a Thread or Runnable class
Call the Helper method you created in the run() of the Thread or Runnable
Inside the Service onStartCommand start the Thread if connection is available
thread.wait/sleep if no connection
I'm not sure I have understanding your request.
With this solution you can play, pause and stop service.
And the service do some work every 60seconds
public class MyService extends Service {
public static boolean testConnexion;
private Timer timer;
#Override
public void onCreate() {
super.onCreate();
timer = null;
testConnexion = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (timer != null) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (testConnexion) {
//StartConnexion
}
}
}, 1000, 60000);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
}
}
In Any activity
To start or stop service.
(Your can call startService many times as you want, there will be just one who will run.)
if (v.getId() == R.id.startService) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
} else if (v.getId() == R.id.stopService) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
To pause action (but not kill the service)
MyService.testConnexion = false;
And for restarting
MyService.testConnexion = true;
Your service is not related to your activity.
If your killing your activity, your service continues to run.
I hope this can help you

How to send Application to background after some specific time

I am using the following code to minimize my app
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
but now I want to minimize my app after some specific time. I mean my app should minimize automatically after 40 - 60 secs etc. I am trying to achieve this through AlarmManager but it is not working.
How I can send my activity to background?
Put the following code in MainActivity.java
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
test();
}
});
}
}, 0, 20000);
The above code will call test() function after 20 second.. Now write the following function...
public void test()
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
Hope this will help.

Categories