Android -9 (P ie) Runnable не запускается должным образом в handler.postAtTime (r3, runnable, time) - PullRequest
0 голосов
/ 24 марта 2020

Android -9 (P ie) Runnable не запускается должным образом в handler.postAtTime (r3, runnable, time). В то время как в Android 8 он работает совершенно нормально.

Для создания исполняемых объектов я использую:

handler.removeCallbacksAndMessages(this.runnableRoom);
    final Runnable r1 = new Runnable() {
        public void run() {
            Log.d("Testrunnable1", " runnable r1 is started for room " + runnableRoom );
            deleteContents(Integer.toString(runnableRoom));
            Intent i = new Intent(myContext, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            myContext.startActivity(i);
        }
    };
    long delayTime = SystemClock.uptimeMillis() + 120000;
    Log.d("Testrunnable1", " runnable r1 is created for room " + item1 );
    this.handler.postAtTime(r1, this.runnableRoom, delayTime);

Для обновления активности из неактивного класса, который я использую

Intent i = new Intent(getApplicationContext(), MainActivity.class);
                String tezx = String.valueOf(i.getFlags());
                if ((Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)) {
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if ((i.getFlags() & i.FLAG_ACTIVITY_NEW_TASK) == 0) {
                        Log.d("Test6.12", "Still Bit value 0");
                    }
                }
                startActivity(i);

Ниже приводится разработанный код, который я использую:

    public static final Handler handler = new Handler(Looper.getMainLooper());
    public boolean addData(String item1, String item2, String item3) {///////1
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(COL2, item1);
            contentValues.put(COL3, item2);
            //contentValues.put(COL4, "new");
            contentValues.put(COL5, item3);
            long result = db.insert(TABLE_NAME, null, contentValues);

            this.runnableRoom = Integer.parseInt(item1);
            handler.removeCallbacksAndMessages(this.runnableRoom);
            final Runnable r1 = new Runnable() {
                public void run() {
                    Log.d("Testrunnable1", " runnable r1 is started for room " + runnableRoom );
                    deleteContents(Integer.toString(runnableRoom));
                    Intent i = new Intent(myContext, MainActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    myContext.startActivity(i);
                }
            };
            long delayTime = SystemClock.uptimeMillis() + 120000;
            Log.d("Testrunnable1", " runnable r1 is created for room " + item1 );
            this.handler.postAtTime(r1, this.runnableRoom, delayTime);

            //if date as inserted incorrectly it will return -1
            if (result == -1) {
                return false;
            } else {
                return true;
            }
        }

public int updateData(String room) {/////
        Log.d("Test6.211", room + " reached database to update ");
        SQLiteDatabase db = this.getWritableDatabase();
        String strSQL = "UPDATE associate_app_sync SET  STATUS = 'loading' WHERE ROOM_NO = '" + room + "'";
        db.execSQL(strSQL);
        Log.d("Test220.2", strSQL);
        db.close();

        this.runnableRoom = Integer.parseInt(room);
        Log.d("Testrunnable1", " runnable r1 should be deleted for room " + room);
        handler.removeCallbacksAndMessages(this.runnableRoom);

        return 1;
    }

    public int updateData2(String room) {/////
            Log.d("Test6.222", room + " reached database to update2 ");
            SQLiteDatabase db = this.getWritableDatabase();
            String strSQL = "UPDATE associate_app_sync SET STATUS = 'assigned'  WHERE ROOM_NO = '" + room + "'";
            String strSQL2 = "UPDATE associate_app_sync SET STATUS = " +
                    "CASE WHEN STATUS = 'new' THEN 'assigned' " +
                    "WHEN STATUS = 'loading' THEN 'assigned'  " +
                    "WHEN STATUS = 'notified' THEN 'notified'  " +
                    "WHEN STATUS = 'assigned' THEN 'assigned'  ELSE 'accepted' END where ROOM_NO = '" + room + "'";

            db.execSQL(strSQL2);
            Log.d("Test220.3", strSQL2);
            db.close();

            long delayTime = SystemClock.uptimeMillis() + 300000;
            this.runnableRoom = Integer.parseInt(room);
            handler.removeCallbacksAndMessages(this.runnableRoom);
            final Runnable r2 = new Runnable() {
                public void run() {
                    Log.d("Testrunnable2", " runnable r2-5min is started for room " + runnableRoom );
                    deleteContents(Integer.toString(runnableRoom));
                    Intent i = new Intent(myContext, MainActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    myContext.startActivity(i);
                }
            };

            //this.delayTime +=  300000 ;
            Log.d("Testrunnable2", " runnable r2 is created for room " + room);
            this.handler.postAtTime(r2, this.runnableRoom, delayTime);

            return 1;
        }

, и эти методы вызываются из другого типа / класса следующим образом

public class MyFirebaseMessage extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    static String[] at_sep;
    static String[] comma_sep;
    public static int openedGroup = -99;
    //public static int currentGroupPosition = -777 ;
    //   public static final Handler handler = new Handler();

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
            try {
                if (at_sep[1].length() != 0 && at_sep[2].equalsIgnoreCase(t2)) {
                    myDB.addData(newEntry, newEntry2, newEntry3);
                } else if (at_sep[2].equalsIgnoreCase(t3)) {
                    myDB.updateData2(newEntry);
                } else if (at_sep[2].equalsIgnoreCase(t4) || at_sep[2].equalsIgnoreCase(t5)) {
                    myDB.deleteContents(newEntry); //myDB.deleteContents(at_sep[1]);
                } else {
                    Log.d("Test007", " Nothing Entered into database as room value not there ");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ((isAppOnForeground(getApplicationContext(), "mns.tcs.com.associateappcallbutton"))) {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                String tezx = String.valueOf(i.getFlags());
                if ((Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)) {
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if ((i.getFlags() & i.FLAG_ACTIVITY_NEW_TASK) == 0) {
                        Log.d("Test6.12", "Still Bit value 0");
                    }
                }
                startActivity(i);
            } else {
                if (at_sep[1].length() != 0 && at_sep[2].equalsIgnoreCase(t2)) {
                    displayNotification(remoteMessage, at_sep[2]);
                }
            }
}}

также из mainActivity метод

package mns.tcs.com.associateappcallbutton;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    public void goToDisplay(int position) {
        notificationReqId = notificationList.get(position).getReqId();
        clickedRoom = notificationList.get(position).getRoomNo();
        Log.d("Test6.2000000", clickedRoom + "|" + notificationList.get(position).getRoomNo() + "|" + notificationList.get(position).getReqId());
        String room_number = notificationList.get(position).getRoomNo();

        if (notificationList.get(position).getStatus().equalsIgnoreCase("new")) {
            myDB.updateData(room_number);
            populateList();
            new CheckStatus().execute();
        } else if (notificationList.get(position).getStatus().equalsIgnoreCase("accepted")) {
            String reqValue = ("Req:Request from Room No." + room_number + " Reached Trial Room.,Open The Door@" + room_number + "@Third@Notification");
            FirebaseDatabase database = FirebaseDatabase.getInstance("https://test1-77841.firebaseio.com/"); //("https://cdr-mns.firebaseio.com/");
            DatabaseReference msgsDBRef = database.getReference("messages");
            try {
                msgsDBRef.child("messageText").setValue(reqValue);
                msgsDBRef.child("isRead").setValue("false");
            } catch (Exception e) {
                Log.d("VariantsActivity", e.getClass() + ": " + e.getMessage() + ": " + e.getCause());
                Log.d("Test3", reqValue);
            }
            myDB.updateData4(room_number);
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(i);
        }
    }

    class CheckStatus extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        @SuppressLint("LongLogTag")
        @Override
        protected String doInBackground(String... strings) {
            Log.d("Test3", notificationReqId);

            try {
                String req_id = notificationReqId;
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("req_id", req_id));
                Log.d("Namevalue pair: ", String.valueOf(params));
                // Creating new JSON Parser
                JSONParser_Read jParser = new JSONParser_Read();
                // Getting JSON from URL
                JSONObject json = jParser.getJSONFromUrl(url, params);
                Log.d("Namevalue json: ", String.valueOf(json));
                // Getting JSON Array
                if (json != null) {
                    Request_ID = json.getJSONArray(TAG_REQ_ID);
                    Log.d("array length: ", String.valueOf(Request_ID.length()));
                    for (int j = 0; j < Request_ID.length(); j++) {
                        JSONObject c = Request_ID.getJSONObject(j);
                        // Storing  JSON item in a Variable
                        reference_request_ID = c.getString(TAG_REF_REQ_ID);
                        clickedRoom = c.getString("room");
                    }
                    Log.d("Test6.200", Request_ID.toString());
                    Log.d("Test6.2000", reference_request_ID + "|" + clickedRoom);
                    sendNotificationToHW(reference_request_ID);
                }
            } catch (Exception e) {
                Log.d("JSON Error ", "JSON Erro");
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String result) {
        }
    }

    private void sendNotificationToHW(String assignedToMe) {
        String room_number = clickedRoom;
        Log.d("Test6.20", clickedRoom + assignedToMe);
        if (assignedToMe.equalsIgnoreCase("true")) {
            Log.d("Test6.21", clickedRoom + assignedToMe);
            myDB.updateData3(room_number);
        } else if (assignedToMe.equalsIgnoreCase("false")) {
            Log.d("Test6.22", clickedRoom + assignedToMe);
            myDB.updateData2(room_number);
        }

        String reqValue = ("Req:Request from Room No." + room_number + " has been Assigned.,Just Assigning@" + room_number + "@Second@Notification");
        FirebaseDatabase database = FirebaseDatabase.getInstance("https://test1-77841.firebaseio.com/"); //("https://cdr-mns.firebaseio.com/");
        DatabaseReference msgsDBRef = database.getReference("messages");
        try {
            msgsDBRef.child("messageText").setValue(reqValue);
            msgsDBRef.child("isRead").setValue("false");
        } catch (Exception e) {
            Log.d("VariantsActivity", e.getClass() + ": " + e.getMessage() + ": " + e.getCause());
            Log.d("Test3", reqValue);
        }

        Intent i = new Intent(getApplicationContext(), MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(i);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("TestonRestart", "refresh list view");
        populateList();
        //notificationListView.setAdapter(new CustomExpAdapter2(this, (ArrayList<NotificationDto>) notificationList, "1"));
        NotificationManager notificationManager1 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager1.cancelAll();
    }
}

Пожалуйста, посмотрите, как все это прекрасно работает в android 8, все исполняемые объекты создаются, переключаются и удаляются в нужное время, но только на устройстве android -9 это исполняемые объекты. не запускаются должным образом.

...