【问题标题】:Why is my service using a lot of battery?为什么我的服务使用大量电池?
【发布时间】:2014-07-20 15:53:49
【问题描述】:

这是我的服务:

public class reminder extends Service{

WakeLock wakeLock;
@Override
public IBinder onBind(Intent arg0) {
    return null;
}
@Override
public void onCreate() {

    super.onCreate();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wakeLock.acquire();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {



    Timer t=new Timer();
    final NotificationManager mgr=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    //check array alarm
    final SharedPreferences settings = getSharedPreferences("arrayalarm", 0);
    final String sport = settings.getString("sport", "");
    final String[] sports=sport.split("#");
    TimerTask tt=new TimerTask() {          
        @Override
        public void run() {

        if(!(sports[0].equals("")))
            for(int i=0;i<sports.length;i++)
            {
                String[] informatins=sports[i].split(":");
                if(new Date().getHours()==Integer.parseInt(informatins[0])&&new Date().getMinutes()==Integer.parseInt(informatins[1]))
                {
                    Notification not=new Notification(R.drawable.sport,"ورزش",new Date().getTime());
                    PendingIntent pn=PendingIntent.getActivity(getApplicationContext(),0,new Intent(getApplicationContext(),MainActivity.class), 0);
                    not.setLatestEventInfo(getApplicationContext(), "ورزش", "تو الان باید ورزش کنی", pn);
                    not.flags=Notification.FLAG_AUTO_CANCEL;
                    not.vibrate=new long[] {1000l,200l,200l,500l};
                    not.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.downloaddlazerdompleted);
                    mgr.notify(1304,not);
                }
            }

                }               
    };
    t.scheduleAtFixedRate(tt, 0, 60000);
    return START_STICKY;
}

@Override
public void onDestroy() {
    wakeLock.release();
    //Toast.makeText(getApplicationContext(), "god bye main human",Toast.LENGTH_SHORT).show();
    super.onDestroy();
}}

我的服务是运动提醒,当特殊时间到来时,我的服务会发送通知。
这很好用,但会消耗大量电池。 在设置>设备中的电池中,我的应用程序排在第一位。
我怎样才能解决这个问题? 我还想在发送通知时打开屏幕。我该怎么做?

【问题讨论】:

  • “我想在发送通知时打开屏幕” 你不能。无论如何,这会消耗更多的电池。另请注意,您在 for 循环的每次传递中都在振动并播放声音……这就是它消耗大量电池的原因。也请使用isEmpty 而不是equals("")

标签: android service battery wakelock


【解决方案1】:

好吧,如果我要编写一个应用程序以尽可能快地耗尽电池,我认为它看起来很像这样。

  • 您持有唤醒锁。这意味着设备无法断电。 ...所以它完全没有理由使用电池
  • 您每分钟都在运行振动器。许多手机上的振动器是一个小型电动机。运行它非常昂贵。

看看AlarmManager。你可以更便宜地做类似的事情。

...包括,顺便说一句,打开屏幕。为此,请勿使用通知。而是向您的 MainActivity 发送 Intent。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多