Android Отправка запросов в фоне

267
12 февраля 2020, 05:30

Нужно отправлять post запрос на сервер, дабы проверить, есть ли уведомления для этого приложения. Как это реализовать, понятия не имею. Использовал один сервис PushBots, с него не идут уведомления на телефоны типа Meizu. Суть такая, пользователь закрыл приложение, занимается своими делами, а фоновые задачи приложения в фоне отправляют запрос каждые 30 секунд и если есть уведомления, уведомляют пользователя

Intent intent= new Intent(this, NotificationListener.getClass()); startService(intent);

Так в MainActivity я объявляю свой сервис

public class NotificationListener extends Service {
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    public NotificationListener() {
    }
    public static final int JOB_ID = 0x01;

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

   @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        editor = sharedPreferences.edit();
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Post post = (Post) new Post().execute("тут url", "user_id=" + sharedPreferences.getInt("userId",0));
                try {
                    ShowNotification(post.get());
                } catch (ExecutionException e) {
                    Log.i("MSG","SOMETHING ERROR " + e);
                } catch (InterruptedException e) {
                    Log.i("MSG","SOMETHING ERROR " + e);
                }
                handler.postDelayed(this, 10000);
            }
        }, 0);
        return START_STICKY;
    }

    private void ShowNotification(String result) {
        JSONObject dataJsonObj = null;
        try {
            dataJsonObj = new JSONObject(result);
            if (dataJsonObj.has("notification")) {
                JSONArray getNotify = dataJsonObj.getJSONArray("notification");
                String content = "";
                for (int i = 0; i < getNotify.length(); i++) {
                    JSONObject notify = getNotify.getJSONObject(i);
                    content += notify.getString("content");
                }
                Intent notifyIntent = new Intent(this, MainActivity.class);
                notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                //builder.setContentIntent(pendingIntent);
                builder.setContentTitle("У вас новый заказ!");
                NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
                bigTextStyle.setBigContentTitle("У вас новый заказ!");
                bigTextStyle.bigText(content);
                builder.setContentText(content);
                builder.setStyle(bigTextStyle);
                builder.setAutoCancel(true);
                builder.setDefaults(Notification.DEFAULT_SOUND);
                builder.setWhen(System.currentTimeMillis());
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setContentIntent(pendingIntent);
                Bitmap largeIconBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
                builder.setLargeIcon(largeIconBitmap);
                builder.setFullScreenIntent(pendingIntent, true);
                Notification notification = builder.build();
                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(1, notification);
                startForeground(1, notification);
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }


}

Android Manifest

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.QUICKBOOT_POWERON" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<service android:name=".NotificationListener"></service>
READ ALSO
Абстракция и её понятие

Абстракция и её понятие

Ты наверняка помнишь, что такое «абстракция» — мы это уже проходилиЕсли вдруг подзабыл — не страшно, вспомним: это принцип ООП, согласно...

236
Нужно пару подсказок по Java

Нужно пару подсказок по Java

В main реализовано бой двух персонажев и у меня почему то время от времени умирают они оба, как можно это исправить и еще одно как создать метод...

278
Динамическое построение PDF-документов

Динамическое построение PDF-документов

Есть андроид приложение, в которое посылает скрипту сайта запрос на формирование PDF документаВыглядит это так:

239
Возникла ошибка при шифровании текста, с подключенным методом генерации помех

Возникла ошибка при шифровании текста, с подключенным методом генерации помех

Возникла следующая проблемаПытаюсь реализовать шифровку текста

252