I am following https://android.googlesource.com/platform/development/+/master/samples/WiFiDirectDemo.
Due to my own requirements ,I just want to run this following code multiple times.
When we click on the search button (cicled in red),The app starts searching for the available wifi peers as shown in the below image
I just want to automate this process every 2 seconds whether it has found some peer or not.
In the code of this Activity:
case R.id.atn_direct_discover:
if (!isWifiP2pEnabled) {
Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
Toast.LENGTH_SHORT).show();
return true;
}
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
return true;
This is the code.
One thing I tried is put everthing in a while(true) loop but i always crash the app.
Then I used a stop button and a flag.This button sets flag to false but it still is not working.
I tried the solution of this :How to automatically Click a Button in Android after a 5 second delay
It does not crash the app but the button only works when i manually click it.
Any suggestions Please ??
What I understood from your problem is you want the task to run without any user intervention to detect new peers and update your UI accordingly.
Run a Handler every 5 seconds when your app is in foreground to start a bound service for searching any new peer, the service will communicate the information back to the activity if it has found anything new or not. When you get the message on your Activity, stop the service and unbind it.
Please see the details about bound service here - https://developer.android.com/guide/components/bound-services.html
You can use Timer class & schedule it to run every 5 seconds. The idea is the timer task doesn't simulate button pressed, but it should does exactly same thing as when the button is pressed.
Assume your Activity class is named MyActivity. Place this in onCreate() of MyActivity class.
Timer myTimer = new Timer();
// schedule to run every 5000 milli seconds
myTimer.schedule(new TimerTask() {
#Override
public void run() {
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// any code that update UI goes here
// Eg: displaying progress indicator, show "finding Peers" text
....
}
});
// the rest of "discover" logic goes here
}
}, 0, 5000);
Related
I have a json response which is loading from api in particular activity in background.This data is for another acitivity which is done to reduce time when landing activity is clicked.
when the landing activity is loaded and if it is on cellular network and at the same time if landing activity is clicked by user then that data is still not loaded i.e it is still loading.
In this state i want to have a check in landing activity that if the data for array is empty then it must show loader and if it is loaded then display data.
Basically can we use async task when there is no network call.In my case network call for data is already done in previous activity I just want to check data in array in background.
or
Is there any another solution to keep check in background.?
Can anyone help?
Please use this timer for specific time to check if data is downloaded or not.
private void startTimer(int timerCount) {
int count = timerCount; // milliseconds for which task eill be running
mTimer1 = new Timer();
mTt1 = new TimerTask() {
public void run() {
mTimerHandler.post(new Runnable() {
public void run() {
if (!YourActivity.isDownloaded) {
} else {
}
}
});
}
};
mTimer1.schedule(mTt1, 1, 1000);
}
Note : Please stop timer when data is downloaded or activity is stopped.
Hope It will help.
I think you could just have a broadcast receiver registered in your landing activity, and then in your previous Activity where your Async task is running, just perform the check in your onPostExecute to see if the data is received correctly, and if yes then send a broadcast which will be received in your landing activity where in, you can then dismiss the loader in your landing activity.
I am Stuck here with this application in android. In my application i am trying to implement a progressbar which shows timer for certain seconds. When the Button is clicked the timer should refresh and again start from 0 in progressBar. For this I am using Thread.
The Problem is, When I Click the button the Thread calls the timer function and each time the thread is getting faster and faster. I couldn't resolve it and not having any idea what is going in background.
This is my code for Timerfunction
public void setTimer()
{
prog=0;
progress.setProgress(prog);
if(flag){
t= new Thread(new Runnable(){
public void run()
{
while(prog<100)
{
prog+=1;
handle.post(new Runnable(){
public void run()
{
progress.setProgress(prog);
if(prog==progress.getMax()&& flag){
call_fun();
}
}
});
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
Log.i("Error", null);
}
}
}
});
t.start();
}
}
I called this function in another function called RandomGeneration. If the button is clicked the randomgeneration is called and the set timer is activated everytime. But the progressbar is running faster after every click. It is constantly running in the same specific time. For example if it runs for 3 seconds in the first click, its running 2 seconds in the second click and getting faster considerably.
Can anyone please try to find what is happening in this code.
Thanks in advance..!!
From what I see a new Thread is being created everytime you click the button.
Maybe try to check if t is already running and if so update it's logic to set progress to 0?
Also, what does if(flag) do?
I have following code snippet in my application activity.
If user is landing on activity for the first time then only thing that will happen is changing the boolean variable shouldSleep to true.
Thereafter, else part will be executed which contains generation of notification at every 60 seconds.
But the main problem is if I execute this code, the activity NEVER gets displayed as it keeps looping in else part and hence go on sleeping.
What I want is remaining application should run normally while every 60 seconds, else part of this method should be executed.I guess it has got something to do with AsyncTask but I don't have much idea about it.
Any idea how to do this? Thanks in advance for your help.
boolean shouldSleep=false;
private void ShowNotification()
{
//DO SOME TASK
if (shouldSleep)
{
Thread.sleep(60000);
//DO SOME TASK
}
else
{
shouldSleep = true;
}
/** Calling the method recursively so that it always runs. */
ShowNotification();
}
Maybe you can use a Timer object :
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//This code is run all 60seconds
myBooleanVar = true;
//If you want to operate UI modifications, you must run ui stuff on UiThread.
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Activity.this.changeUiStuff();
}
});
}
}, 60000);
Just use a Timer. Instead of a thread approach, you could run your task every 60s:
new Timer().schedule(task, delay, period);
with period = 60*1000
I need to use idle listener to listen the user is using the application or idle when the activity is alive.
I need to do something when the user is not using the application more than ten seconds.
How can i make it possible?
Here is the idea how you can achieve this task:
Firstly you need a Runnable(), which will be Run when your timeout(e.g. 10 sec) occurs. Below is the Runnable():
private Runnable DoOnTimeOut = new Runnable()
{
public void run()
{
// Do something Here
}
}
Now, in your activity, you can call postDelayed for the DoOnTimeOut:
Handler hl_timeout = new Handler();
#Override
public void onCreate(Bundle b)
{
hl_timeout.postDelayed(DoOnTimeOut, 10000); // The DoOnTimOut will be triggered after 10sec
}
Now, most important part is that when you see user interaction, you want to cancel the call to DoOnTimeOut and then again set the call for next 10 sec. Here is the Override method of your Activity for User Interaction:
#Override
public void onUserInteraction()
{
super.onUserInteraction();
//Remove any previous callback
hl_timeout.removeCallbacks(DoOnTimeOut);
hl_timeout.postDelayed(DoOnTimeOut, 10000);
}
I hope it will be helpful for you.
I am having 10 different buttons in my application for different task to perform. I want to develop one service which continuously check (listens) and if user is not clicking any button for particular time let say for 5sec than i wish to perform some other task. How can I check that user has not clicked any button? If anyone having any idea please kindly let me know.
You could simply set a Timer to the desired length. When a button is clicked, just reset the timer. Start the timer in onResume so it starts even if the user is coming back from a phone call or other activity. You should probably stop the timer in onPause of the activity too.
In each of your click listeners save off the time the last button was clicked:
private long lastClickTimestamp;
private Handler handler = new Handler();
public void onCreate( Bundle saved ) {
BackgroundJob job = new BackgroundJob();
handler.postDelayed( job, SECONDS_TO_WAIT * 1000 );
button1.setClickListener( new OnClickListener() {
public void onClick( View view ) {
lastClickTimestamp = System.currentTimeInMillis();
// do the listener logic for button 1 here.
}
});
button2.setClickListner( new OnClickListener() {
public void onClick( View view ) {
lastClickTimestamp = System.currentTimeInMillis();
// do the listener logic for button 2 here.
}
});
// repeat that for all 10 buttons.
}
Now the smarter developer would create a reusable base class that handled setting the timestamp once, then reuse that base class in each of the 10 buttons. But, that's left up to you. Then the background job would look like:
public class BackgroundJob implements Runnable {
private boolean done = false;
// meanwhile in job:
public void run() {
if( lastClickTimestamp > 0 && System.currentTimeInMillis() - lastClickTimestamp > SECONDS_TO_WAIT * 1000 ) {
// let's do that job!
}
if( !done ) {
// reschedule us to continue working
handler.postDelayed( this, SECONDS_TO_WAIT * 1000 );
}
}
}
If you have to use a service you can send a notification to the service saying a button was clicked, then the service can keep track of the time when that occurred. I wouldn't use a service for this because playing an animation or sound doesn't need to survive if the app is put into the background or killed. Services are meant for things like playing music when someone is doing something else, chat applications, or things that need to run in the background when the user isn't interacting with the application. What you're describing could be done as I've shown because when the user gets a phone call or text message they'll leave your application, and the animation or sound you're playing probably should stop too. Pretty easy to do with the Handler option I showed. More difficult, but doable, with a service.
On each button click, update some Calendar object to a new Calendar instance and then you can check what the time is of that Calendar and see if it's more than 5 minutes ago.
//this is a field
Calendar calendar;
public void onClick(View v) {
calendar = Calendar.getInstance();
//etc
switch(v.getId()) {
}
}