What/How 提供服务的最佳方式 运行? (例如,每分钟检查一次 wifi,如果禁用它)

What/How the best way to make service running ? (checking every minute for wifi for example, if on disable it)

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

那么,问题来了 .. 让我们以 WiFi 为例,我已经添加了 wifi 代码检查,如果它已启用 = 关闭它,现在可以吗?

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

但是,我不希望我的应用消耗电池,应用的主要思想是节省电池,而不是耗尽电池。

我已经在服务中添加了该方法,当用户点击应用时,它 运行s,但只有一次,如果他启用了 wifi ..没有任何反应,他需要 re-enable选项.

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

刚刚使用了 AlarmManager,现在我遇到了问题,我添加了 SwitchPreference,当它启用时它将 运行 警报,但是因为它太长/太复杂而无法制作,我已经使用了“ 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
}

}

我遇到的问题是,当开关打开时,代码会工作(这正是我想要的)但是当我禁用开关时,它会保持 运行ning,它不会' t cancel .. 那么如何在开关关闭时停止闹钟?

我使用了上面解释的共享首选项。

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

启动服务

希望对你有所帮助:)

您可以使用 AlarmManager 来安排每 60 秒调用您的服务,或者使用 BroadcastReceiver 来通知 WiFi 状态变化。