Search code examples
androidservicealarmmanager

Call a service class Once in a day when application is Starts in android ,with less Battery Consumption


I want to call a Service Class, when User Starts the Application Once in a Day in Android.

Manifest Code:

<service android:name=".DailyRemainder" >
            <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </service>

Java Code:

 // for Repeating Process
    Intent myIntent = new     Intent(sign_in.this,.DailyRemainder.class);
    pendingIntent1 = PendingIntent.getService(sign_in.this, 0,myIntent, 0);
   AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
   Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(System.currentTimeMillis());
     calendar.add(Calendar.SECOND, 20); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent1);

Above code is running in background drains my Mobile Battery, but i need when user starts the Application that time Service Should Run Once in a Day. How to Achieve this.


Solution

  • I found the answer for my Question using Shared pref.

    When Activity is Starting ,First time in a day Async task will run. then inside on Post execute todays date is saved.

    after that async will not execute in a same day. I removed Alarm Manager part

    // Shared Preferences
        SharedPreferences settingsShrepref;
    
        // Editor for Shared preferences
        SharedPreferences.Editor editor;
        // Sharedpref file name
        private static final String PREF_NAME = "MyPrefFileShred";
    
        // User name (make variable public to access from outside)
        public static final String KEY_TODAY_DATE_ANDTIME = "TimeToday";
    

    Inside Oncreate Activity

        /* Added Servcie count Once in a day Fetch from Server*/
    
                try {
    
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
                    Date date = new Date();
                     TodayDate_String = dateFormat.format(date);
    
    
                    settingsShrepref = getSharedPreferences(PREF_NAME, 0);
                    editor = settingsShrepref.edit();
    
                    String Val=settingsShrepref.getString(KEY_TODAY_DATE_ANDTIME,"");
    
    
                    Log.i("Stored Val", Val);
                    Log.i("Today date", TodayDate_String);
                    if(!Val.equals(TodayDate_String))
                    {
    
                        //for  SYNC web to Local
                        try
                        {
                            Log.d("Comments", "FirstTime Started");
    
                            // get Internet status
                            isInternetPresent = cd1.isConnectingToInternet();
    
                            // check for Internet status
                            if (isInternetPresent)
                            {
                                new AsyncCallWSCategoryCOUNTFetch().execute();
    
                            }
                            else {
    
                                Log.i("CATEGORY COUNT ", "Not Internet ......!");
                            }
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            Log.i(" CATEGORY COUNT ", "EXCEPTION in reading Data from Web Async task ONstart ......!");
    
                        }
    
    
                    }
                    else
                    {
                        Log.d("Comments", "Second TIme");
    
                        Getmethod();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("", "Exception here Run Service.");
                }
    

    Inside Async task On post Execute

    @Override
            protected void onPostExecute(Void result)
            {
                Log.i(TAG_CategoryCOUNT, "onPostExecute");
    
    
                try {
    
    
    
                    //the app is being launched for first time in a Day, do something
                    Log.d("Comments", "First Time");
    
                    // Storing name in pref
                    editor.putString(KEY_TODAY_DATE_ANDTIME, TodayDate_String);
                    // commit changes
                    editor.commit();
    
                    String Val=settingsShrepref.getString(KEY_TODAY_DATE_ANDTIME, null);
                    Log.d("after Insertion data Date", Val);
    
    
    
                } catch (Exception e) {
    
                    e.printStackTrace();
                }
    
            }