在Android中推送通知服务

时间:2017-05-18 12:48:35

标签: java android

我正在尝试在Android Studio中制作一个应用程序,它使用服务每15秒发送一次推送通知。问题是当我弹出通知时,我测试代码的手机的动作非常慢。当我使用模拟器时,它工作正常。有谁知道是什么让这段代码变得非常慢?

提前致谢!

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;
}
}

0 个答案:

没有答案