祝你有个愉快的一天。 我也在60秒内使用AlarmManager服务运行我的应用程序。 我的问题是这个过程消耗了大量电池,我该如何解决? 提前感谢您的回答。
警报管理员代码。
Intent myIntent = new Intent(MainActivity.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(
MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= 19) {
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
utcMillisNextMin(), 60000, pendingIntent);
return;
} else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
utcMillisNextMin(), 60000, pendingIntent);
return;
}
public long utcMillisNextMin() {
Time t = new Time();
t.setToNow();
t.second = 0;
t.minute++;
return t.normalize(true);
}
警报服务代码。
public class AlarmService extends Service {
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getApplicationContext().getPackageName());
if (mWakeLock != null && !mWakeLock.isHeld()) {
mWakeLock.acquire();
}
startService();
return START_NOT_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
private void startService() {
alarmHandler.sendEmptyMessage(0);
}
private Handler alarmHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
rootFonksiyon();
//rootFonksiyon in: SharedPreferences are saved when comparing data //and notification to the user.
if (mWakeLock != null) {
mWakeLock.release();
}
stopSelf();
}
};
}
<service android:name="---.AlarmService" android:enabled="true" />
抱歉我的英文不好