'Android : with Broadcast Reciever : Notifications are somtimes received at time and sometimes are not recieved at all

Android: with BroadcastReceiver: Notifications are sometimes received at the time and sometimes are not received at all

Tracing the log ---> onReceive() are sometimes called and sometimes are not called which is very strange.

Testing is done on real device --> Note 10 ( Android 12 )

No clear error appears in the log :(

Below are the codes, Appreciate your kind help

---------------------------
public class MainActivity extends AppCompatActivity {

private static final String TAG = "tag";
String url ;
String city;

EditText msearchet;
Button msearchbtn;


SharedPreferences sharedPreferences;

int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){

                requestPermissions(new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 1000);

            } else {

                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                try {
                    city = hereLocation(location.getLatitude(), location.getLongitude());

                    msearchet.setText(city);


                } catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this,"not found, thanks to enable the location and reopen the application",Toast.LENGTH_SHORT).show();
                }
            }




    msearchbtn.setOnClickListener(new View.OnClickListener() {
       @RequiresApi(api = Build.VERSION_CODES.O)
       @Override
        public void onClick(View v) {

        
           NotificationCheckPoint();
           String mcity = msearchet.getText().toString().trim();
            if (mcity.isEmpty()){
               Toast.makeText(MainActivity.this,"Please enter location",Toast.LENGTH_LONG).show();

            }else{

               url = "https://muslimsalat.com/"+mcity+".json?key=3dae215d2876988441baa2029544a647";
                //url = "https://www.google.com";
                searchLocation();

            }
        }
    });

    retrieveData();



   
}

@Override
protected void onPause() {

  saveData();
  super.onPause();
}


private void searchLocation() {

    //if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){

      //  requestPermissions(new String[] {Manifest.permission.INTERNET}, 1000);

    //} else {
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading....");
        pDialog.show();

        JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

       // StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
               // new Response.Listener<String>() {

                    @Override
                    public void onResponse(JSONObject response1) {
                        //get the data from json
                        //Log.d(TAG, response.toString());
                       // Toast.makeText(MainActivity.this,"Success"+response1.toString(),Toast.LENGTH_LONG).show();
                        try {
                            String mfajr = response1.getJSONArray("items").getJSONObject(0).get("fajr").toString();
                            String mdoher = response1.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
                            String maser = response1.getJSONArray("items").getJSONObject(0).get("asr").toString();
                            String mmaghreb = response1.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
                            String masha = response1.getJSONArray("items").getJSONObject(0).get("isha").toString();
                            String mday = response1.getJSONArray("items").getJSONObject(0).get("date_for").toString();

                            fajr.setText(mfajr);
                            doher.setText(mdoher);
                            aser.setText(maser);
                            maghreb.setText(mmaghreb);
                            asha.setText(masha);
                            day.setText(mday);



                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error
                        VolleyLog.d(TAG, "Error:" + error.getMessage());
                        Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_SHORT).show();
                        pDialog.hide();

                    }
                });


}


private String hereLocation (double lat, double lon){

    String cityName = "";

    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses;
    try {
        addresses = geocoder.getFromLocation(lat, lon, 10);
        if(addresses.size() > 0){

            for(Address adr:addresses){
                if(adr.getLocality() != null && adr.getLocality().length() > 0){

                    cityName = adr.getLocality();
                    break;
                }
            }
        }
    } catch (IOException e){

        e.printStackTrace();
    }

    return cityName;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {

        case 1000: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                try {
                    city = hereLocation(location.getLatitude(), location.getLongitude());

                    msearchet.setText(city);

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "not found, thanks to enable the location and reopen the application", Toast.LENGTH_SHORT).show();
                }

            } else {

                Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
}


public void saveData(){

    sharedPreferences = getSharedPreferences( "saveData", Context.MODE_PRIVATE );


    sharfajr = fajr.getText().toString();
    shardoher = doher.getText().toString();
    sharasr = aser.getText().toString();
    sharmaghrib = maghreb.getText().toString();
    sharisha = asha.getText().toString();
    sharday = day.getText().toString();

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("key fajr", sharfajr);
    editor.putString("key doher", shardoher);
    editor.putString("key asr", sharasr);
    editor.putString("key maghrib", sharmaghrib);
    editor.putString("key isha", sharisha);
    editor.putString("key day", sharday);

    editor.commit();
    Toast.makeText(getApplicationContext(), " your message is saved", Toast.LENGTH_LONG).show();
}

public void retrieveData(){

    sharedPreferences = getSharedPreferences("saveData", Context.MODE_PRIVATE);

    sharfajr = sharedPreferences.getString("key fajr", null);
    shardoher = sharedPreferences.getString("key doher", null);
    sharasr = sharedPreferences.getString("key asr", null);
    sharmaghrib = sharedPreferences.getString("key maghrib", null);
    sharisha = sharedPreferences.getString("key isha", null);
    sharday = sharedPreferences.getString("key day", null);


    fajr.setText(sharfajr);
    doher.setText(shardoher);
    aser.setText(sharasr);
    maghreb.setText(sharmaghrib);
    asha.setText(sharisha);
    day.setText(sharday);



}

public void NotificationCheckPoint(){

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 18);
    calendar.set(Calendar.MINUTE, 33);
    calendar.set(Calendar.SECOND, 5);
    //calendar.add(Calendar.HOUR_OF_DAY, 02);
    //calendar.add(Calendar.MINUTE,33);
    //calendar.add(Calendar.SECOND, 0);
    Log.d("MyAPP", "123");

    Intent i = new Intent(getApplicationContext(),Notification_Receiver.class);
    Log.d("MyAPP", "456");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,i,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    Log.d("MyAPP", "789");
    //PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),100,i,PendingIntent.FLAG_IMMUTABLE);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

}

}

===================================

public class Notification_Receiver extends BroadcastReceiver {

public final String CHANNEL_ID = "3";
@RequiresApi(api = Build.VERSION_CODES.S)
@Override
public void onReceive(Context context, Intent intent) {
    Log.d("MyAPP", "onReceive() called");
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"3", NotificationManager.IMPORTANCE_DEFAULT);

    NotificationManager manager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);

    Notification.Builder builder = new Notification.Builder(context,CHANNEL_ID);
    builder.setSmallIcon(R.drawable.alert);
    builder.setContentTitle("Title175");
    builder.setContentText("Notification text");
    //builder.setPriority(Notification.PRIORITY_DEFAULT);

    NotificationManagerCompat compat = NotificationManagerCompat.from(context);
    compat.notify(1,builder.build());


}

}

======================================================================

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company.newsalah">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


<application
    android:allowBackup="true"
    android:name=".AppController"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.Newsalah">
    <receiver android:name=".Notification_Receiver" android:enabled="true"/>
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source