让服务运行的最佳方式是什么/如何运行?(例如,如果打开并禁用wifi,则每分钟检查一次)



我正在制作一个应用程序,其中包括一些需要每分钟检查的内容。

所以,这是quesiton。。以WiFi为例,我添加了WiFi代码检查,如果启用=关闭,现在可以吗?

我的问题是,这种方法只发生一次,我希望它每分钟检查一次,如果wifi打开=>就关闭。

但是,我不想让我的应用程序吃掉电池,应用程序的主要想法是节省电池,而不是杀死电池。

我在一个服务中添加了这个方法,当用户点击应用时,它会运行,但只有一次,如果他启用了wifi。。什么都没发生,他需要重新启用这个选项。

标题可能很长,但没有更好的东西:p

刚刚使用了AlarmManager,现在我遇到了一个问题,我添加了SwitchPreference,当它被启用时,它将运行Alarm,但由于它太长/太复杂,我使用了带有布尔值的"sharedpreferences",如下代码所示:

        boolean WiFiEnabled = prefs.getBoolean("WiFiEnabled", false);
        prefs.getBoolean("WiFiLowSpeedEnabled", false);
        if(pref == mWiFiEnable)
        {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("WiFiEnabled", true);
            editor.commit();
        }

我的警报如下:

public class Alarm extends BroadcastReceiver
{
 @Override
public void onReceive(Context context, Intent intent)
{
    // Put here YOUR code.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean WiFiEnabled = prefs.getBoolean("WiFiEnabled", false);
    if(WiFiEnabled)
    {
        Toast.makeText(context,"WiFi Enabled, Alarm",Toast.LENGTH_LONG).show();
        if(!MainService.isConnectedWifi(context))
        {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if(wifiManager.isWifiEnabled()){
                wifiManager.setWifiEnabled(false);
            }
        }
    }


}
public void SetAlarm(Context context)
{
    AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, Alarm.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 5, pi); // Millisec * Second * Minute
}
}

我遇到的问题是,当开关打开时,代码会工作(这是我想要的),但当我禁用开关时,它会继续运行,不会取消。。那么,当开关关闭时,如何停止警报呢?

我使用了如上所述的共享偏好。

您可以使用AlarmManager每60秒安排一次对服务的呼叫,也可以使用BroadcastReceiver来通知WiFi状态更改。

在服务类中,您需要覆盖onStartCommand方法,然后使用Intent serviceIntent = new Intent(this, ServiceName.class); startService(serviceIntent); 启动服务

希望对您有所帮助:)