I am tryiny to update my edittext in UI. I have a service from where I send a intent by clicking a button and update in the UI. Everything works fine. But I would like to send intent without button click.
What I tried was to put my Intent in a method and call it oncreate in service but even then it been just called once.
public class myService extends service {
onCreate{
sendMessage();
}
private void sendMessage(){
Intent intent = new Intent("com.example.app.SEND");
intent.putExtra("KEY", (String) Number);
sendBroadcast(intent);
}
When I do like this, I just send empty string which is not useful. And even then just once.
Can I send intent continously ? So that It updates my UI once it receives input ? Any possible way to do it ?
I would like to send intent every 5 seconds.
You can use TimerTask with IntentService for scheduled jobs.
ex:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
//some execution
}
};
timer.schedule(timerTask, 5000, 5000);
Related
I have this Runnable method which send a notification once it is called and every minute sends a JSON Post on an HTTP Server. So i coded the method "sendNotification" to keep informed the user regards the "service" is running but when I close the app, the method to send the JSON stops and the notification stays active on the notification bar. I would like to close the notification as well.
//Runnable methods for frequency position
private final Runnable oneMinuteRunnable = new Runnable() {
#Override
public void run() {
sendNotification();
getTimestamp();
new Thread(new Runnable() {
#Override
public void run() {
getLocation();
doPostRequest();
}
}).start();
handler.postDelayed(this, 60 * 1000);
}
};
This is the notification method
//Make notification when the frequency service is running
public void sendNotification() {
Notification notification = new NotificationCompat.Builder(this, com.example.httptracker.Services.Notification.NOTIFICATION_ID)
.setSmallIcon(R.drawable.ic_baseline_run_circle_24)
.setContentTitle("AMP Tracker")
.setContentText("Tracker is running")
.build();
compat.notify(1, notification);
}
I looked up online and I saw only solutions with a Service class but I would need to develop a "stop service" button to cancel the notification. But it is not what I need. The notification should disappear once the app is closed or the method killed.
Thanks in advance
try to cancel your notification with:
compat.cancel(1); // assuming compat is NotificationManager instance, 1 is your id
in e.g. onDestroy of Activity or any place when your app is stopping oneMinuteRunnable looped execution
I have an Android project which is sending a Broadcast every second and am trying to figure out how to stop it after a click.
My broadcast code is:
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
stoptimertask(); //it is stopping broadcast for a second.
You can define two methods: one that start a Timer to send a broadcast every second and a second one that stop the Timer.
Timer timer;
private void startBroadcastLoop() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Send broadcast
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
}
},0,1000); // Send broadcast every second
}
private void stopBroadcastLoop() {
if(timer!=null){
timer.cancel();
timer = null;
}
}
And then on your button, call the right function according to the state of a boolean:
sendBroadcastBool = false;
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// If broadcast not sent yet
if (!sendBroadcastBool) {
startBroadcastLoop();
sendBroadcastBool = true;
}
else {
stopBroadcastLoop();
sendBroadcastBool = false;
}
}
});
Best
As a Unity3D developer, I've created an application and exported it to Android Studio. My client is asking me to make this app go back to foreground after 10 seconds of user's inactivity (in case the user opens another app). I've tried to create a service that is started on the OnPause function of my UnityPlayerActivity. Then the service would detect the user's inactivity and launch my app again (putting it back to foreground). First I've only tried to use Time.Schedule to launch my app after 10 seconds no matter what, but everytime the application is paused (goes to background), it starts the service and then it crashes. The question is: is there a simple way to do this? I'm not an Android Java Developer (only know the basics) and I'm struggling with this part .
I'm trying to create this Service and then I try to start it from the onPause() function in my activity. When I pause the app on my phone the app crashes. Can anyone tell me if I'm on the right way and, please, help me?
public class ReturnToForeground extends Service {
public ReturnToForeground() {
}
// constant
public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
Intent intent = new Intent(this, UnityPlayerActivity.class);
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
return super.onStartCommand(intent, flags, startId);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// do action
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
}
});
}
}
}
Make a timer for when the app is in the onPause(), when the timer reaches 10 seconds you should pass an intent which will make your app active again (let's say taking the user back to the main view). You can save the current data of your app in something like shared preffs, so that information wont be lost in most situations.
In many cases this problem appears when a resource which you are trying to reload is not active anymore inside the application.
From the info you have shared it seems like you are not starting the service correctly. It would be nice if you can add a crash log so that we can debug it and see where is the problem.
TL;DR: My intent takes too much time to start from a different thread, whereas starting from the main thread is very fast. I dont actually know if this is a problem with threads or with the onFinish method
So, I have a countdown timer. It counts down from twenty seconds, and onFinish() I have an intent. I am also periodically setting the text of my textView based on millisUntilFinished. I noticed, that after the textView says 1 second left, the intent starts after 3 seconds.
But, if I am switching activities by using an intent from OUTSIDE of the onFinish method the next activity starts quickly. So,
Why does starting an intent from a the onFinish method take longer than usual?
According to my little test with my timer, I decided that I need a better and faster way to start my intent, since clearly, the onFinish method launches after more time then the timer actually starts. So, what should I do to start my intent faster? I need it to be immediate...
public void startTimer() {
timer = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished/1000;
timetext.setText(seconds + ":00");
}
public void onFinish() {
Intent intent = new Intent(MainActivity.this, GameOver.class);
intent.putExtra("score", score); // pass your values and retrieve them in the other Activity using keyName
intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
startActivity(intent);
}
}.start();
}
Thanks,
Ruchir
Try placing the startActivity(intent) outside of the timer as such:
public void startTimer() {
timer = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished/1000;
timetext.setText(seconds + ":00");
}
public void onFinish() {
Intent intent = new Intent(MainActivity.this, GameOver.class);
intent.putExtra("score", score); // pass your values and retrieve them in the other Activity using keyName
intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
}
}.start();
startActivity(intent);
}
You can have a try :
public void onFinish() {
cancel(); //Cancel the countdown
Intent intent = new Intent(MainActivity.this, GameOver.class);
intent.putExtra("score", score); // pass your values and retrieve them in the other Activity using keyName
intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
startActivity(intent);
}
`
hi
When my app get the ACTION_BOOT_COMPLETED it starts a service.
I would like to delay that for lets say 60sec.
Can i do that in the:
public class StartAtBootServiceReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
// Delay...60sec
}
}
use Timer() and TimerTask():
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//run your service
}
}, 60000);
When you receive the BOOT_COMPLETED intent you should use the AlarmManager to setup an pending intent that will fire after 60 seconds.