I have app with timer. When I press the power button, my app going to sleep mode and stopped timer. What should I do to timer continue to working. Below my very simple code timer.
Thread t = new Thread(){
#Override
public void run() {
while (!isInterrupted()){
try {
Thread.sleep(1000);
i++;
Log.e("pokaz "," i "+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
I solved my problem. I write this code in activity
PowerManager pm;
PowerManager.WakeLock wl;
pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
and layout write this code
android:keepScreenOn="true"
but now my application is in background and version API is kitkat evrything is ok. When test my aplication in API lolipop and goes on sleep mode and next turn on phone I see message "unfortunately myApp has stopped". Why?
To work your app in background you need to use Service, IntentService or BroadCastReceiver.
And do your thread work inside Service.
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
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.
Yesterday and today I tried to solve the problem from my service. I read lots of topics about this problem (when i want unstopable timer every 15s) but i don't find any solution.
First i try asynch task and service which are nevertheless implement WakeLock still pause when I disconnect the charger. In this topic i read that is no chance to do this in Service. (Here)
Now i try the AlertManager but i read that from some version of android don work repeting in small intervals.
My questions here is, How can i do this (15s interval which can be run always (sleep mode, no on charge etc..)) and android don't be stop this task. I need regular renewal every 15 seconds in all circumstances.
Someone help me how to do this?
Thank
My service on create
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
wakelock.acquire();
runnable = new Runnable() {
public void run() {
while(true) {
if (!running) return;
if (updateVillages()) {
result = true;
if (isNewVillage()) {
if (isNotificationEnable) doNotificate();
}
System.out.println("Prebehlo overovanie");
} else {
result=false;
System.out.println("Není internetové pripojenie");
}
updateUI();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread= new Thread(runnable);
thread.start();
I am struggling with persistent problem with Android app that has MQTT ServiceConnection running on background. When ever I switch to an other application that has fullscreen surface (game, youtube on fullscreen, etc) the application completely freezes when trying to bring it on front again. It even refuses to relaunch if closed from drawer. The app won't reopen unless completely killed. The weird thing is that if I run the application via debugger it works perfectly. It makes the problem difficult to get handle on. I have put on prints on beginning of each life cycle method, even before call to super class method. None of them get printed when the app hangs, which hints that it hangs some where on the system level.
Now if I call stopService at onStop method, it works fine but defeats the purpose of having persistent service on the background. I have called unbindService also on onStop, but it does not help. With all the other application everything works fine, even you tube as long as it is not used in fullscreen.
The dependency to the MQTT library is
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
and this is my onStop() method
#Override
protected void onStop() {
FirebaseUserActions.getInstance().end(getIndexApiAction0());
if(mBoundToService) {
try {
unbindService(serviceConnection);
mBoundToService = false;
}
catch (Exception e)
{
e.printStackTrace();
}
}
super.onStop();
}
And the onStart() method would be this:
#Override
protected void onStart() {
Log.d(TAG, "onStart has been called");
super.onStart();
if(!mBoundToService) {
bindService(mqttIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
FirebaseUserActions.getInstance().start(getIndexApiAction());
}
But this never gets called. From the logs I can see that MQTT service is receiving messages and produces no errors. Messages continue to be received even as the application is hanged so the background service is alive and running.
The inlined Service connection class is like this:
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder)
{
mqttService = ((MQTTService.MyBinder) binder).getService();
mBoundToService = true;
Log.d(TAG,"MQTT service has been bound");
Handler handler = getHandler();
//NOTIFY THE LOGIN ACTIVITY THAT THE DATA HAS BEEN ACQUIRED
Message msg = handler.obtainMessage(Utils.HANDLE_MQTT_SERVICE_CONNECTED);
Bundle bundle = new Bundle();
bundle.putString(Utils.KEY_MQTT_SERVICE_BOUND,"Everything is complete");
msg.setData(bundle);
handler.sendMessage(msg);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBoundToService = false;
Log.d(TAG, "MQTT service has been UNbound");
}
};
The MQTT service is started like this from onCreate():
mqttIntent = new Intent(getApplicationContext(), MQTTService.class);
if(!mBoundToService){
Log.d(TAG,"Starting MQTT Intent");
startService(mqttIntent);
Log.d(TAG,"Binding MQTT Service");
bindService(mqttIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
Am I missing something that I should be doing at the onStop() to be able to resume the application after having fullscreen application on front?
I am facing an issue that on button touch i start recording audio in my android application, but when i plays the recorded audio it is missing some duration of the recorded audio.
Here is my code snippet to start recording voice on a button touch given by:
public void start() {
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
try {
myRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
myRecorder.start();
text.setText("Recording point: Recording...");
}
On sensing touch event i starts calling this start(); function.
Can any body tell me any alternative solution? I faced this issue on my glaxy s3 android device.
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
The piece of code above takes some time, hence the delay between the user pressing the button (start() being called) and the recorder actually starting the recording (myRecorder.start()).
You should initialize the recorder and get it ready before the button is pressed. Just move the above piece of code elsewhere, e.g. onCreate(). Since I don't know the context of this code, I cannot tell you exactly where.