I need to write an application to open the browser (sample site www.onet.pl), which will restart every 3 hours. The commotion of restart was displayed. I managed to create such a layout, but I can not handle the cyclical restart. Please help where to add and what code? One class is enough.
This is my code:
public class MainActivity extends AppCompatActivity {
private Object v;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start(null);
m_Runnable.run();
}
public void start(View v) {
Uri uri = Uri.parse("http://onet.pl");
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
this.mHandler = new Handler();
}
private final Runnable m_Runnable = new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
MainActivity.this.mHandler.postDelayed(m_Runnable, 15000);
}
};
}
You could use a timer instead of Runnable.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
//and put the rest of your code here
}
},0,5000);
Related
So I have this code, that has a countdown timer in a service with a 10 second timer. What I want to do is in the onFinish() method I want to launch the Activity (which is called MainActivity) automatically even when I am outside the app.
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
Try This to open your main activty after 10 second.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// launch your main activity here and finish your current activity
}
}, 10000);
}
Probably you will have to override lifecycle method's and also use PARTIAL_WAKE_LOCK to keep cpu running untill you finish execution, in case user lock screen.
If you are inside a service then simply launch you activity using intent. Put this code in your onFinish() method:
Intent i = new Intent();
i.setClass(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
You neet to pass an activity context to your TimeDisplayTimerTask :
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
private Activity mActivity;
public TimeDisplayTimerTask(Activity activity){
mActivity = activity;
super();
}
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
if (activity != null {
Intent startIntent = new Intent(activity, MainActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startIntent);
}
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
I need some help with my first Android project.
I want to write a app which is showing you a picture with a ImageView for a few seconds I would say so about 4 seconds and after that it change to a second activity which shows a button(only for testing).
My Problem is that my app after I started it in my AVD jump over the picture and shows immediately the button.
How can I fix it? I looked up so long and tried so many things I hope someone of you have a idea :)
Thanks for helping
Here my Code of my MainActivity:
package com.example.parkourspots;
public class MainActivity extends Activity {
private ViewTreeObserver vto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
vto = myLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
});
}}
Check this code.
package com.example.parkourspots;
public class MainActivity extends Activity {
private static int TIME_OUT = 4000; //Time to launch the another activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(MainActivity.this, ActivityTwo.class);
startActivity(i);
finish();
}
}, TIME_OUT);
}
});
You can try:
public class MainActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler.postDelayed(new Runanble() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); // 4 seconds
}
}
In addiction, you may add this for your second activity declaration in AndroidManifest: android:finishOnTaskLaunch="true"
never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive.
But this is an fast and alternative solution for your problem.
public class MyActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(new Runnable() {
public void run() {
doStuff();
}
}, 5000);
}
private void doStuff() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}
Then 5 seconds after the intent must start.
But i recommend async task
1)Sleeping 500 only sleeps for .5 seconds. So it would blink quickly anyway
2)Sleeping doesn't allow the thread to get back to the looper, so it freezes your UI. This means it won't update and draw anyway. Use a timer instead. Or posting a message to a handler would be acceptable here.
The problem is you're only sleeping for 500 milliseconds (half of one second), so it makes sense that it happens seemingly-immediately. You're also going to want to remove the OnGlobalLayoutListener after it's called. Here's an example of an approach that should work for you:
final Handler handler = new Handler(); // Create a Handler on the main Thread
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
removeOnGlobalLayoutListener(vto, this);
handler.postDelayed(new Runnable(){
public void run(){
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); //Post back to the main Thread after 4000 mils (4 seconds)
}
});
#SuppressLint("NewApi")
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
if (Build.VERSION.SDK_INT < 16) v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
else v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
Proper and short solution
Make a handler and give them a delay to call back itself:
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 1s
}
}, 1000);
Remember that 1 sec = 1000 milliseconds
Adjust time with that formula.
Happy Coding.
i have a quiz game for my android that has a time limit. what i want is there is a choices button that if you click one of the buttons it you will be automatically intent to the class next level but if you didnt answer or click any of the button you will be intent to the other class, thats why the game has a time limit. my problem is i dont know how to put a time limit that will intent or transfer you in another class automatically if you didnt click any of the button choices. i tried sleep but what happen is even i already clicked the correct answer and im on the next level class it will sleep to the class i intented to my sleep. please help me with my problem. i also try handler but didnt work
public class EasyOne extends Activity {
Button a, b, c;
TextView timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (Button) findViewById(R.id.btn_ea1);
b = (Button) findViewById(R.id.btn_eb1);
c = (Button) findViewById(R.id.btn_ec1);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
private Runnable task = new Runnable() {
public void run() {
Handler handler = new Handler();
handler.postDelayed(task, 5000);
Intent intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};
You should use a handler but in order to cancel the timeout you must remove the delayed message from the handler in your click listener code.
public class EasyOne extends Activity {
static private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 123) {
((EasyOne) msg.obj).onTimeout();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (Button) findViewById(R.id.btn_ea1);
b = (Button) findViewById(R.id.btn_eb1);
c = (Button) findViewById(R.id.btn_ec1);
Message msg = mHandler.obtainMessage(123,this);
mHandler.sendMessageDelayed(msg,5000);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
mHandler.removeMessages(123,this);
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
private void onTimeout() {
//your code
}
}
Here's my code:
public class SomeName extends MapActivity implements OnClickListener, OnTouchListener{
public Timer t1 = new Timer();
public TimerTask tt;
public long interval = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.map);
timer();
}
public final void timer()
{
t1 = new Timer();
tt = new TimerTask() {
#Override
public void run() {
systemClick();
}
};
t1.scheduleAtFixedRate(tt, 10000, interval);
}
public void systemClick()
{
Toast.makeText(getApplicationContext(),"System Button Clicked", 5).show();
}
Actually, I want to call some function, where I refresh my location.
But I can't understand why I never get the toast on the screen.
I'm new to android.
Thanks for any help.
use handler in your Activity
final Handler handlerforadd = new Handler();
Runnable runnableforadd = new Runnable() {
#Override
public void run() {
handlerforadd.postDelayed(this, 1000);
}
};
handlerforadd.postDelayed(runnableforadd, 0);
The reason is the Toast has to be done on the UI thread. In your current code the method run() is being executed on a separate thread. I would suggest looking at this article on Processes and Threads. #parag is correct using a Handler is one way to get a reference to the UI thread but there are other methods.
Hello and thanks in advance for any advice you can offer with the following problem. I have a simple Activity that shows an AlertDialog. It works fine if I instantiate the AlertDialog in the constructor. If, however, I move the AlertDialog to another method, one triggered by a Timer event, nothing happens and I see no errors:
public class RecipesPage extends Activity
{
private WebView browser;
private Timer timer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes);
browser = (WebView)findViewById(R.id.webkit);
browser.getSettings().setJavaScriptEnabled(true);
browser.loadUrl("file:///android_asset/html/index.html");
TimerTask task=new TimerTask() {
public void run() {
notifyMe();
}
};
timer.schedule(task, 10000);
}
private void notifyMe()
{
new AlertDialog.Builder(this)
.setTitle("MessageDemo")
.setMessage("eek!")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing -- it will close on its own
}
})
.show();
}
}
Use a Handler instead of TimerTask - it will run your Runnable on the UI thread.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes);
browser = (WebView)findViewById(R.id.webkit);
browser.getSettings().setJavaScriptEnabled(true);
browser.loadUrl("file:///android_asset/html/index.html");
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
public void run() {
notifyMe();
}
}, 10000L);
}