android .view.windowmanager $ ошибка badtokenexception, указывающая на «WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE» - PullRequest
0 голосов
/ 18 марта 2020

после того, как я опубликовал свое приложение на консоли разработчика Google, я начинаю получать сообщения об ошибках на своей консоли cra sh отчет , и это первая деталь ошибки , большинство ошибок связанный с сервисом, работающим в фоновом режиме телефона, этот сервис показывает маленькое окно с текстом внутри каждые 1 мин. Обратите внимание, что эта ошибка возникает только для некоторых пользователей, и я не могу воспроизвести ее, и приложение отлично работает на каждом Устройство, которое я протестировал. если у вас есть опыт работы с такими ошибками, сообщите мне, если вы доступны, и пришлите мне цену.

это java файлов службы, работающей в фоновом режиме:

public class ReminderService extends Service {

private WindowManager windowManager;
private View reminderView;

private Handler handler;
private Handler handlerSM;

private TextView reminderText;
private RelativeLayout borderLayout;
private String[] reminderColors;


CircleImageView CircleImageSM;
ImageView closeButton;


public ReminderService() {
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    reminderView = LayoutInflater.from(this).inflate(R.layout.reminder_layout, null);


    //Add the view to the window.

    final WindowManager.LayoutParams params;

    int LAYOUT_FLAG;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
    } else {
        LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
    }

    params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            LAYOUT_FLAG,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);


    //Specify the chat head position
    params.gravity = Gravity.TOP | Gravity.END;        //Initially view will be added to top-left corner
    params.x = 0;
    params.y = 100;

    params.windowAnimations = android.R.style.Animation_Translucent;


    //Add the view to the window
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    windowManager.addView(reminderView, params);


    //Change Animations According to your wish


    reminderText = reminderView.findViewById(R.id.reminderText);
    borderLayout = reminderView.findViewById(R.id.reminderLayout);
    reminderColors = this.getResources().getStringArray(R.array.reminderColors);



    GradientDrawable drawable = (GradientDrawable) borderLayout.getBackground();
    drawable.setStroke(3, Color.parseColor(reminderColors[PreferencesUtil.getBorderColor(this)])); // set stroke width and stroke color
    drawable.setColor(Color.parseColor(reminderColors[PreferencesUtil.getBackgroundColor(this)])); // set stroke width and stroke color

    reminderText.setTextColor(Color.parseColor(reminderColors[PreferencesUtil.getFontsColor(this)]));

    reminderText.setTextSize(TypedValue.COMPLEX_UNIT_PX, (PreferencesUtil.getFontSize(this) + 12) * getResources().getDisplayMetrics().scaledDensity);


    reminderText.setText(getReminderText());


    Typeface face = ResourcesCompat.getFont(this, GlobalValues.fonts_ids[PreferencesUtil.getFontFamiy(this)]);


    reminderText.setTypeface(face);


    reminderText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            stopSelf();

        }
    });



    handler = new Handler();

    reminderDismissRunnable.run();

}


private String getReminderText() {

    ArrayList<String> remindersList = new ArrayList<String>();

    if (PreferencesUtil.getArrayReminders(this) != null) {

        remindersList = PreferencesUtil.getArrayReminders(this);

    }

    else {

        String[] azkar = getResources().getStringArray(R.array.athkarArray);

            for(int i=0; i<azkar.length; i++){
                remindersList.add(azkar[i]);
            }

            PreferencesUtil.setArrayReminders(this, remindersList);


        }


    //ArrayList<String> remindersList = PreferencesUtil.getArrayReminders(this);

    Integer lastReminder = PreferencesUtil.getLastReminder(this);

    if (lastReminder + 1 <= remindersList.size() - 1) {

        PreferencesUtil.setLastReminder(this, lastReminder + 1);
        return remindersList.get(lastReminder + 1);

    } else {
        PreferencesUtil.setLastReminder(this, 0);
        return remindersList.get(0);
    }
}


private Runnable reminderDismissRunnable = new Runnable() {
    @Override
    public void run() {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopSelf();
            }
        }, (PreferencesUtil.getDuration(ReminderService.this) + 1) * 1000);
    }
};



@Override
public void onDestroy() {
    super.onDestroy();

    handler.removeCallbacks(reminderDismissRunnable);

    if (reminderView != null) windowManager.removeView(reminderView);


}
}

и это файл ReminderHandlerService java:

public class ReminderHandlerService extends Service {

int pos=0;

private Handler handler;

@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    handler = new Handler();

    startReminderService();

    return START_STICKY;
    //return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "my_channel_01";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "اشعار بان التطبيق يشتغل في خلفية الهاتف", NotificationManager.IMPORTANCE_DEFAULT);

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, "my_channel_01")
                .setContentTitle("تطبيق اذكاري")
                .setContentText("تطبيق اذكاري يشتغل في خلفية الهاتف").build();
        startForeground(1, notification);


    }

}


Runnable runReminder = new Runnable() {
    @Override
    public void run() {


        try {
            if(isInteractive()) {
                startService(new Intent(ReminderHandlerService.this, ReminderService.class));
            }

        } finally {


            int a= PreferencesUtil.getInterval(ReminderHandlerService.this);

            if (a == 5) {
                pos = a + 5;

            } else if (a == 6) {
                pos = a + 9;

            } else if (a == 7) {
                pos = a + 13;

            } else if (a == 8) {
                pos = a + 22;
            } else if (a == 9) {
                pos = a + 51;
            } else if (a == 10) {
                pos = a + 110;
            } else if (a == 11) {
                pos = a + 169;
            } else if (a == 12) {
                pos = a + 228;
            } else if (a == 13) {
                pos = a + 287;

            }else{
                pos=a;
            }

            handler.postDelayed(runReminder, (pos + 1) * 1000);
        }
    }
};

public void startReminderService() {

    runReminder.run();
}

public boolean isInteractive() {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    KeyguardManager myKM = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
     if( powerManager.isInteractive()&&powerManager.isInteractive()&&!myKM.isKeyguardLocked() ){
         return true;
     }else{
         return false;
     }

}


@Override
public void onDestroy() {
    super.onDestroy();

    handler.removeCallbacks(runReminder);

}
}
...