当应用程序在 android 中启动时,每天调用服务 class 一次,电池消耗更少

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

我想调用服务 Class,当用户在 Android 每天启动一次应用程序时。

舱单代码:

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

Java代码:

 // 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);

以上代码是 运行 在 背景耗尽我的手机电池 , 但我需要当用户启动 应用程序时服务应该 运行 一次 一天。如何实现。

AlarmManager 只是可以 100% 唤醒您的设备的功能。

任何服务如果不做任何工作,根本不会消耗您的电池。我认为你必须更仔细地阅读你的代码。

尽管如此,一些建议。 您可以调用广播接收器而不是服务来唤醒。 即使用

Intent intent = new Intent("yourBroadCastString");
PendingIntent pi = PendingIntent.getBroadcast(...);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.KITKAT){
            am.setExact(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
        } else{
            am.set(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
        }

上面的情况am.setExact真的很耗电,

在这种情况下要唤醒您的设备,您必须使用内部广播:

PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                    PowerManager.ACQUIRE_CAUSES_WAKEUP |
                    PowerManager.ON_AFTER_RELEASE, _.APPNAME + Integer.toString(index));
        if (wakeLock != null && wakeLock.isHeld()){
            wakeLock.acquire();
        }

ComponentName comp = new ComponentName(ctx.getPackageName(),
                yourServiceClass.class.getName());
        startWakefulService(ctx, intent.setComponent(comp));

里面androidmanifest.xml

<receiver android:name="yourBroadCast">
        <intent-filter>
            <action android:name="yourBroadCastString"/>
        </intent-filter>
        </receiver>

而且你的代码真的很糟糕:

天哪,这到底是什么东西? Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); long t = calendar.getTimeInMillis(); 我认为你必须阅读你的代码。

如果您还想保持设备唤醒或唤醒设备以提供服务,请使用this

因为运行在应用程序启动时一天一次很容易做到,只需在任务完成时使用SharedPreferences来存储,以便用户再次打开任务时进行简单检查在 SharedPrefs 中应该防止相同的任务再次 运行。

我使用共享首选项找到了问题的答案。

当 Activity 正在启动时,一天中的第一次异步任务将 运行。然后在 Post 执行今天的日期被保存。

之后异步将不会在同一天执行。 我删除了警报管理器部分

// 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";

内部 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.");
            }

内部异步任务在 post 执行

@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();
            }

        }