Android: Redirect to another Activity after delay - java

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)

Related

I'm trying to hit API request from a broadcast receiver, can anyone mention correct way of doing it?

public class GetReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SharedPrefHelper sharedPrefHelper = new SharedPrefHelper(context);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(1);
if (intent != null) {
if (intent.getStringExtra("result") == "ok") {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(Web.Register.User_Id, sharedPrefHelper.getUserId());
jsonObject.addProperty(Web.BookingRequest.ACTIVITY, "ok");
new BasePresenter<>().createApiRequest(BaseApplication.getRetrofit().create(ApisHelper.class)
.okResponse(jsonObject), new BaseCallBack<BasicApiModel>() {
#Override
public void onCallBack(BasicApiModel output) {
if (Log.isLoggable("qwert", Log.DEBUG)) {
Log.d("qwert", "Receiver's onCallBack: " + output.getMessage());
}
}
});
} else {
Log.d("qwert", "onReceive: testing_cancelled");
}
}
}
what is the correct way of starting api request from receiver ?
Don't start any long running task in your broadcast receiver, otherwise your app may crash if onReceive runs more than 10 sec.
It's better to trigger a service from onReceive method and put your network operation inside the service.
Also keep in mind to use intent service / any other service depending on your requirement, with a worker thread to run your network operation so that your UI thread doesn't get blocked.

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);

stopping a handler thread button

Every 5 sec I want to current latitude longitude to the web application in Android app. if the user login to the app in that we using user logs by placing a button's. If the user hits log out button I need to stop the handler thread current run on same activity page by a different button (Log in )
I have done everything but while stopping the threads my application get crashed
if the user hit login button it automatically sends the data for every 5 sec
private void techlocation() {
handler = new Handler ();
locationManager = (LocationManager) User_deatils .this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // Choose your accuracy requirement.
locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(User_deatils.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(User_deatils.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 8000, 10, (LocationListener) User_deatils .this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 8000, 10, (LocationListener) User_deatils .this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
handler.postDelayed(runLocation, 5000);
}
This is the runnable threads sends data to server-side
public Runnable runLocation = new Runnable() {
#Override
public void run() {
latitude = String.valueOf(lat);
longitude = String.valueOf(lon);
arrLat.add(latitude);
arrLng.add(longitude);
User_deatils.this.handler.postDelayed(User_deatils.this.runLocation, 50000);
handler.removeCallbacksAndMessages(this);
Log.e("msg", "new" + handler);
}
}
log in button
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
.// SaveButtonState("b3");
techlocation(); // calling handler threads
}
});
log out button
b4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacksAndMessages(runLocation);
}
});
To start runnable and do work every 5 seconds do this.
Declare runnable this way with a boolean.
// flag that should be set true if handler should stop
boolean mStopHandler = false;
private Handler mHandler;
//initialize runnable in oncreate()
mHandler=new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// do your stuff here
if (!mStopHandler) {
mHandler.postDelayed(this, 5000);
}
}
};
Call this to start this runnable on button click()
// start runnable
mHandler.post(runnable);
And finally use this to stop runnable
handler.removeCallbacks(runnable);

Alarm ringing stops when cleared from ram

I am making an alarm clock which asks user to do a particular work in order to close the alarm when it rings. It is working fine but the problem is that if the user closes the alarm app from the recent activities while the alarm is ringing, the alarm stops ringing. I want that even if the user clears the app while its ringing, it should not stop ringing. It should only stop once the task given is completed. How can I implement this?
Edit #1: Activity that is called when alarm rings
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(LOG_TAG, "in AlarmAlert");
unlockScreen();
setContentView(R.layout.activity_alarm_alert);
Bundle bundle = this.getIntent().getExtras();
alarm = (Alarm) bundle.getSerializable("alarm");
alarmDatabase = new AlarmDatabase(this);
//Uri uri = alarm.getRingtonePath();
question = (TextView)findViewById(R.id.question);
answer = (TextView) findViewById(R.id.answer);
oldColors = answer.getTextColors();
diff = alarm.getDifficulty().toString();
questionString = GenerateMathsQuestion.generateQuestion(diff);
question.setText(questionString);
actualAnswer = EvaluateString.evaluate(questionString);
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int result = am.requestAudioFocus(focusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setVolume(1.0f, 1.0f);
mediaPlayer.setLooping(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
try {
mediaPlayer.setDataSource(this, Uri.parse(alarm.getRingtonePath()));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
if(alarm.getIsVibrate()) {
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = {1000, 200, 200, 200};
vibrator.vibrate(pattern, 0);
}
}
public void closeAlarm(){
Log.v(LOG_TAG, "will now stop");
mediaPlayer.stop();
if(vibrator!=null)
vibrator.cancel();
Log.v(LOG_TAG, "will now release");
mediaPlayer.release();
Log.v(LOG_TAG, "id of ringing alarm: " + alarm.getAlarmId());
alarm.setIsActive(false);
alarmDatabase.updateData(alarm);
cursor = alarmDatabase.sortQuery();
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(AlarmDatabase.COLUMN_UID));
currentAlarm = alarmDatabase.getAlarm(id);
Log.v(LOG_TAG, "id of next alarm " + id);
if(currentAlarm != null) {
if (currentAlarm.getIsActive() == true) {
currentAlarm.scheduleAlarm(this, true);
break;
}
}
}
this.finish();
}
You should use Services. Take a look at it, that is what you want it. Generally you can make it to run an operation, and a service wont return any result. But it runs indefinitely even when you kill the app from task manager or free RAM.
I suggest this tutorial for reading about services.
UPDATE
Implement your activity with the service in the following way so it can talk with the layout and stops the alarm when required.
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}

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

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);

Categories