Android app wont run a second time - android

I have an Android app that shows a frame-by-frame animation activity. At the end of the animation it starts a background service and closes the activity. Here is the code:
cont = getApplicationContext();
final ImageView img = (ImageView)findViewById(R.id.img);
img.setBackgroundResource(R.drawable.intro);
img.post(new Runnable() {
public void run() {
animation = (AnimationDrawable)img.getBackground();
animation.setOneShot(true);
animation.start();
timer = new Timer();
timer.schedule(new timer_exp(), 3400);
}
});
}
class timer_exp extends TimerTask{
#Override
public void run() {
//start service
Intent serviceIntent = new Intent(cont, MainService.class);
startService(serviceIntent);
//kill activity
finish();
}
}
When I run the app I can see the animation and then the service starts. When I press on the app's icon again, I get a black screen and the app crashes.
Any Ideas to what the problem might be?
Thanks,
PB

After some investigation, it turned out that the service was the problem.
I had some Thread.sleep() in several places that caused the UI thread to crash.
After adding another thread for these actions the problem solved.

Related

Auto Redirect When User Is Taking Too Long Input In Activity Android

I have a scenario, which when a User Rating, or inputting on a data, then the current Activity will Time it to the setted time.
So, if the User isn't do Anything, or taking the Action to Long, then the current Activity will direct the User into the MainActivity.
In my case, i have a Rating app, which is located in a Public place. I thought that if People wants to Rate BUT not completing the Quiz phase, then i don't want to leave the last Quiz to meet the new People who wants to Rate.
I've tried using these code:
int timeout = 4000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Intent homepage = new Intent(Quiz2.this, MainActivity.class);
startActivity(homepage);
finish();
}
}, timeout);
And these one:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Quiz2.this, MainActivity.class));
}
}, 4000);
It works, but it didn't work as expected, as it apply to ALL of the activities (I mean, after these code works in Current Activity, the Rest of the Activities is Applied and Timed too)
I don't want this. What i want is to Apply these Timer ONLY in Current Activity.
How this can be done?
Appreciate for any help, Regards.
I didn't fully understand what you actually wanna do,
but I'm guessing using CountDownTimer and then starting the other activity when the timer finished should do the trick.
new CountDownTimer(4000, 1000) {
public void onTick(long millisUntilFinished) {
// You could show the user the time left using `millisUntilFinished`
}
public void onFinish() {
// Do something when the timer is finished (start your activity & finish)
}
}.start();

Reusing timer in android

In my android app, I have the following relevant piece of code:
/*Code outside*/
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask(){
public void run(){
stuffToBeDone();
}
},someVariableDelay,someVariablePeriod);
}
}
Everything was going fine until I noticed that stuffToBeDone() was running once for every time I pressed the button. As far as I understand, every time onClick() is called and the old Timer should not exist anymore, but somehow the TimerTask survives.
In the second button click, I no longer have a reference to the first Timer to cancel() it (because it should not exist anymore). And if I declare the Timer as a final variable in the Code outside so that I can do it, after canceling I cannot reuse it anymore. So how can I terminate that TimerTask but then still be able to use a Timer?
Android Timer is thread based from the Android Developers website:
http://developer.android.com/reference/java/util/Timer.html
When a timer is no longer needed, users should call cancel(), which releases the timer's thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.
I would recommend instantiating the timer inside the onclicklistener only i.e. something similar to this:
/*Code outside*/
Timer t = null;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(t == null)
t = new Timer();
else
t.cancel();
t.scheduleAtFixedRate(
new TimerTask(){
public void run(){
stuffToBeDone();
}
},someVariableDelay,someVariablePeriod);
}
}

Add the loading screen in starting of the android application

My app is loading the start page in 10 seconds. In that time of 10 sec android screen is blank.
In that time I want to add the loading screen. How to add it?
And tell me in app how to know the starting page is loading? And tell me how to do in my app?
use ProgressDialog.
ProgressDialog dialog=new ProgressDialog(context);
dialog.setMessage("message");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
hide it whenever your UI is ready with data. call :
dialog.hide();
You can use splash screen in your first loading Activity like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000); //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
Hope this code helps you.
Please read this article
Chris Stewart wrote there:
Splash screens just waste your time, right? As an Android developer,
when I see a splash screen, I know that some poor dev had to add a
three-second delay to the code.
Then, I have to stare at some picture for three seconds until I can
use the app. And I have to do this every time it’s launched. I know
which app I opened. I know what it does. Just let me use it!
Splash Screens the Right Way
I believe that Google isn’t contradicting itself; the old advice and
the new stand together. (That said, it’s still not a good idea to use
a splash screen that wastes a user’s time. Please don’t do that.)
However, Android apps do take some amount of time to start up,
especially on a cold start. There is a delay there that you may not be
able to avoid. Instead of leaving a blank screen during this time, why
not show the user something nice? This is the approach Google is
advocating. Don’t waste the user’s time, but don’t show them a blank,
unconfigured section of the app the first time they launch it, either.
If you look at recent updates to Google apps, you’ll see appropriate
uses of the splash screen. Take a look at the YouTube app, for
example.
You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res folder and make a class like this :-
public class LoadingScreen {private ImageView loading;
LoadingScreen(ImageView loading) {
this.loading = loading;
}
public void setLoadScreen(){
final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
final Handler loadingHandler = new Handler();
Runnable runnable = new Runnable() {
int loadingImgIndex = 0;
public void run() {
loading.setImageResource(loadingImages[loadingImgIndex]);
loadingImgIndex++;
if (loadingImgIndex >= loadingImages.length)
loadingImgIndex = 0;
loadingHandler.postDelayed(this, 500);
}
};
loadingHandler.postDelayed(runnable, 500);
}}
In your MainActivity, you can pass a to the LoadingScreen class like this :-
private ImageView loadingImage;
Don't forget to add an ImageView in activity_main.
After that call the LoadingScreen class like this;
LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();
I hope this will help you
public class Splash extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 3000; //set your time here......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
}
If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.
If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :
ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{
#Override
public void run()
{
try
{
sleep(10000) //Delay of 10 seconds
}
catch (Exception e) {}
handler.sendEmptyMessage(0);
}
} ;
t.start();
//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
pd.dismiss();
//Start the Next Activity here...
}
};
Write the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000) //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}

calling an activity without any click event - android

Iam an newbie to android.I don't know whether this question may sound silly but i didn't find any solution.Please bare me. I had created an application which will first loads the app logo. I need to call another activity after this without using any click event.can anybody help me out wit this? and also i need to know in windows we can place panels over another panel. Can we do the same ting android? If yes how can i achieve that? I know that in a layout we have to place views but my questions is can we design view over another view so that i can hide and show views whenever needed?
Thanks in advance
Using Timers or Threads is a horrible way to do this, you are inviting memory leaks into your app. Use Android's Handler instead:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
// create Intent for next activity and call startActivity with it
}
}, 2000);
If you have a reference to your content view, use contentView.getHandler() instead of creating a new one.
By the way, if this is for a personal project, consider NOT USING SPLASH SCREENS
You do not really provide enough information to give you a proper answer, but this will start a timer and when 5000 milliseconds has elapsed it will switch to another activity:
public class SplashActivity extends Activity {
private Timer t;
public void onCreate(Bundle b) {
super.onCreate(b);
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, NextActivity.class);
startActivity(i);
}
}, 5000);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent();
intent.setClass(WelcomePage.this, HomePage.class);
startActivity(intent);
}
}
};
timer.start();
}
that should do the trick my friend!!

How to update textview text which is update in service class

I have developed an app with start, pause, resume and finish buttons.
It works properly in the activity using thread and handler.
If the user clicks on the start button a thread is started and displays textviewHH:MM:SS time and the rest of the buttons work correctly as well.
Problem:
If the activity goes to background then how do I update the textview time? I have made services for this task but, how do I take the response from services to UI?
Please, could you give me any idea of how to do it or any other possible solution?
You can create CustomBroadcast
Here is sample code.
Try this, it will work..
In YourService.Java
public static final String BROADCAST_ACTION = "com.example.tracking.updateprogress";
intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
In YourActivity.Java
registerReceiver(broadcastReceiver, new IntentFilter(YourService.BROADCAST_ACTION));
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Update Your UI here..
updateUI();
}
}
You can also pass data in Intent.
If you create a simple new Thread(new Runnable() {...}) within the Activity you can run UI manipulations with the runOnUiThread(new Runnable() { // your UI modify method }) Acitvity method. If the Activity go to the background the Thread is still running.

Categories

Resources