0

I am trying to make an app in Android Studio which sends a push notification every 15 seconds, using a service. The problem is that the mobiles I tested the code on acted really slowly when a notification pops up. When I use an emulator, it works fine. Does anyone know what makes this code really slow?

Thanks in advance!

MainActivity.java

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent i = new Intent(this, MyService.class);
    startService(i);

}
}

MyService.java

public class MyService extends Service {
public MyService() {
}

public void showPushNotification (){

    NotificationCompat.Builder pushbericht;
    final int IDnummer = 123;
    pushbericht = new NotificationCompat.Builder(this);
    pushbericht.setAutoCancel(true);
    pushbericht.setSmallIcon(R.drawable.icoontje);
    pushbericht.setContentTitle("Poll App");
    pushbericht.setContentText("Hoi");

    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    pushbericht.setContentIntent(pendingIntent);

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.notify(IDnummer, pushbericht.build());
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                long futureTime = System.currentTimeMillis() + 15000;
                while (System.currentTimeMillis() < futureTime) {
                    synchronized (this) {
                        try {
                            wait(futureTime - System.currentTimeMillis());
                            showPushNotification();


                        } catch (InterruptedException e) {
                        }
                    }

                }
            }
        }
    };
    Thread thread = new Thread(r);
    thread.start();
    return Service.START_STICKY;
}

@Override
public void onDestroy() {

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
}
litelite
  • 2,857
  • 4
  • 23
  • 33
Niels
  • 1
  • 1
  • `while (System.currentTimeMillis() < futureTime)` the system is going to loop really fast for 15 second. With time it might drain quite a lot of energy from the phone. You should consider using [`Thread.sleep(int);`](http://stackoverflow.com/a/13765159/3072566) – litelite May 18 '17 at 12:54
  • @litelite thank you for the comment! I changed it but it didn't make the app any faster, unfortunately. – Niels May 18 '17 at 13:11

0 Answers0