Device is lagging on Notification and Recent Apps because of my application - android

Don't know if this is the right place to ask this question but I noticed that when I have my application in the Recent Apps, the Recent Apps becomes very laggy until I remove it in there. This also applies to when I receive notification from my app, swiping down the notifications is very slow until I dismiss the notifs for my app.
Anyone experienced something like this? I'm not sure what to look for and I don't know what might have caused this. Any insight will be very helpful. Thanks

After spending hours and hours with trial and error I am pretty sure to get it fixed. The solution looks very weird, but as I said, for me it did the trick.
Please try this:
Create a utility class (Utils.java), and nest this method inside:
public static void runOnBackgroundThread(final Callable callable) {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
callable.call();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
Modify your notification class processing the update on the background.
Pseudo code:
public void update(final long totalRx, final long totalTx) {
Utils.runOnBackgroundThread(new Callable() {
#Override
public Object call() throws Exception {
// do your calculations and/or content changes
mNotificationManager.notify(Const.NOTIFICATION_NETWORK, mBuilder.build());
return null;
}
});
}
Hope it helps.

Related

How to implement an Android Service in Xamarin.Forms

I'm trying to periodically check with a web service if a new item has been added to a database. If there's a new item a listview that the user sees should be updated.
I'm using PCL and I have accomplish it creating a new Task with a timer inside. But this only works if the app is open. I want to do the same when the app is closed so the user gets a notification when a new item is added remotely.
I've been doing some research and I found andoid services, the info said that the service will continue, regardless of the app state, until you tell it to stop. But i haven't found many examples in how to implement it.
Here's the code that I had that works only when the app is opened:
Task.Run(() =>
{
Device.StartTimer(TimeSpan.FromSeconds(secs), checkUpdates);
});
bool checkUpdates()
{
if (isOnline)
{
var lastUp= Application.Current.Properties["lastUpdate"] as string;
//returns true if a new item is added
if (service.newItem(DateTime.Parse(lastUp)))
{
var itm = service.getNewItem(DateTime.Parse(lastUp));
Device.BeginInvokeOnMainThread(() =>
{
notification.ShowNotification(itm.Title, 1000);
listView.Insert(0, itm);
}
});
}
App.Current.Properties["lastUpdate"] = DateTime.Now.ToString();
}
return true;
}
I'm trying to do the same with an Android service using dependency services, here's what I've got so far:
public interface IService
{
void Start();
}
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context, typeof(DependentService));
Android.App.Application.Context.StartService(intent);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
return StartCommandResult.NotSticky;
}
}
The problem is that I don't know how to implement the code that I had in the timer to the service, can someone please help?
For what you want to achieve, you should probably look at the AlarmManager
Have a look at this StackOverflow post, where there's an example for one and maybe this one as well. The second one is Java but it might give you an idea of what you might deal with
EDIT:
You might also want to have a look at these Xamarin.Android documents around Services and BroadcastReceivers, to get better understanding with what you're dealing

What is happening in Android when i run Thread.sleep in background service

What is happening in Android if I have IntentService defined as following:
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
run();
}
private void run() {
try {
while(true)
{
//Some expensive Internet & SQL querying stuff
Thread.sleep(1000 * 60 * 60);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
How bad will it drain the battery?
I aim for rather fundamental answer (What will happen if I set the sleep to 1 day)?
You question to so close to this one. He also trying to do some work inside a loop and make the Thread sleep.
From the Geeks answer in the provided question, I can tell you that it depends on the //Some code line and what will you replace it with. You might replace it with an intensive code that use the internet, GPS, Flash, Camera and consume your battery for sure OR you might replace it with nothing and let the Thread sleep which allow the CPU to replace it with any other Thread that needs to perform anything.

Android - Proper way to listen for variable change, and do something upon change?

The app I'm making requires that a bit of code be executed whenever the value of a particular variable changes from 0 to 1.
The handler example below is the method I'm currently using to do this (I copied it from someone else).
I have a feeling it's not a proper method though because having just three of these handlers in my app causes the UI to be fairly unresponsive, and causes the device (a phone) to become quite hot.
As you can see, I've put 10ms delays in the handlers to try to deal with this.
Isn't there something more like OnClickListener that can listen at all times for a variable value change without putting such stress on the CPU?
I'm pretty new to Java and Android so a simple example would be very much appreciated.
final Handler myHandler1 = new Handler();
new Thread(new Runnable()
{
#Override
public void run()
{
while (true)
{
try
{
Thread.sleep(10);
myHandler1.post(new Runnable()
{
#Override
public void run()
{
if (myVariable == 1)
{
myVariable = 0;
//do stuff
}
}
});
} catch (Exception e) {}
}
}
}).start();
You must set your variable via a setter method. Then, you can be reactive to that change.
public void setMyVariable(int value) {
this.myVariable = value;
if (myVariable == 1) {
doSomethingWhen1();
} else if (myVariable == 0) {
doSomethingWhen0();
}
}
A more elegant way to do that will be an observer pattern, Here you can find more detailed documentation about it.
You must certainly avoid while(true) loops on mobile device, it will drain your battery and you are also blocking the UI thread. That's the reason why your UI is unresponsive and your cellphone it's quite hot.

Is it possible to bind an activities to this service which works on background thread and always running?

It's my first question on SO, I hope this question won't be bad.
I have a service, it starts working when user launchs an app and works until user will kill it via task killer or turn off his device.
This service has a background thread which does some work with data. I need to bind activities (from activities, not by service) and sometimes (1-2 times per 30 seconds) send data to binded activities.
Structure of my service:
public class myserv extends Service {
public static boolean started=false;
public class workwithdata extends Thread {
#Override
public synchronized void start() {
super.start();
//.. Not important.
}
#Override
public void run() {
if (running) return;
while (true) {
if(condition) mythread.sleep(30000);
else {
Object data = recieveMyData();
if (!data.isEmpty()) {
//.. Some work with recieved data, not important.
sendDataToBindedActivities(data); //This is what I need.
}
mythread.sleep(10000);
}
}
}
}
#Override
public void onCreate() {
super.onCreate();
this.started=true;
mythread = new workwithdata();
mythread.start();
}
}
Well, I found one question but my problem has a little differences: I don't need to send any data to the service, I need just send some data to all binded activities (which service doesn't know at all).
Structure for which I'm looking for:
public class myact extends Activity {
#Override
public void onCreate(Bundle bun) {
super.onCreate(bun);
if(!myserv.started) {
Intent service = new Intent(getApplicationContext(), myserv.class);
getApplicationContext().startService(service);
}
bindToService(this);
}
#Override
public void onRecievedData(Object data) {
//work with recieved data from service "myserv".
}
}
I also tried to find some solutions in android documentation but I didn't find what I need.
So, main question is: is it possible to work with communications from service to activities?. If no: What should I use for this purpose? If yes, just, sorry, can I ask for some code or class names, because I tried to find and didn't...
Thank you.
You need to use a RemoteCallbackList
When your clients bind to the service, you will need to register them using RemoteCallbackList.register().
When you want to send data to the bound clients, you do something like this:
int count = callbackList.beginBroadcast();
for (int i = 0; i < count; i++) {
try {
IMyServiceCallback client = callbackList.getBroadcastItem(i);
client.onRecievedData(theData); // Here you callback the bound client's method
// onRecievedData() and pass "theData" back
} catch (RemoteException e) {
// We can safely ignore this exception. The RemoteCallbackList will take care
// of removing the dead object for us.
} catch (Exception e) {
// Not much we can do here except log it
Log.e("while calling back remote client", e);
}
}
callbackList.finishBroadcast();
An example can be found here It is kinda complicated, but maybe you don't need everything this offers. In any case, have a look.

Queuing threads in Android

my app wants to update pictures on the web on a regular basis. This doesn't require UI feedback, so I just start a new Thread and let it run. The problem is, that this update-method may be called before the previous one has been finished. How can I make sure that the second call doesn't start a new thread but is queued and automatically started when the previous one finished? Are handlers the right solution here as well?
Here the code:
public static void updatePictureOnPicasa(final PictureEntry pe) {
new Thread() {
public void run() {
try {
if(pe.isUpdated())
picasa.updatePicture(pe.getUrl(), pe.getDescription(), pe
.getTags());
} catch (Exception e) {
Log.e(Prototype.TAG, "Unable to update picture on Picasa "
+ pe.getUrl());
}
}
}.start();
}
You can use a service feature in Android.Please refer these links:
http://www.brighthub.com/mobile/google-android/articles/34861.aspx
http://marakana.com/forums/android/examples/60.html
Hope this will help you.

Categories

Resources