Как отправить уведомление, когда конкретный мобильный телефон Wifi BBSID (в общих настройках) подключен к Wi-Fi BBSID со службой?

У меня есть один BBSID в моих общих предпочтениях. Всякий раз, когда пользователь подключается к сети Wi-Fi, моя служба должна проверять, является ли он тем же BBSID, что и тот, который хранится в SharedPreferences. Я реализовал приведенный ниже код, но проблема в том, что уведомление создается несколько раз при подключении к сети Wi-Fi.

public class WifiConnectionNotificationService extends Service {
BroadcastReceiver mReceiver;
String bssid = "64:66:b3:f0:ce:81";
/*
WifiConnectionNotificationService(String ssid) {
    this.ssid = ssid;
}*/

// use this as an inner class like here or as a top-level class
public class IsWifiConnectedBroadcastReceiver extends BroadcastReceiver {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (intent.getAction().contentEquals("android.net.wifi.STATE_CHANGE") || intent.getAction().contentEquals("android.net.conn.CONNECTIVITY_CHANGE")) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            if (wifiManager.isWifiEnabled()) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
                    if (wifiInfo.getBSSID().contentEquals(bssid)) {
                        PushNotification(context);
                    } else {
                        if (Context.NOTIFICATION_SERVICE != null) {
                            notificationManager.cancelAll();
                        }
                    }
                }
            } else {
                if (Context.NOTIFICATION_SERVICE != null) {
                    notificationManager.cancelAll();
                }
            }
        }
    }
}

@Override
public void onCreate() {
    // get an instance of the receiver in your service
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.wifi.STATE_CHANGE");
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    mReceiver = new IsWifiConnectedBroadcastReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification(Context context) {
    NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context);
    Intent notificationIntent = new Intent(context, Register.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    //set
    builder.setContentIntent(contentIntent);
    builder.setSmallIcon(android.R.drawable.ic_notification_clear_all);
    builder.setContentText("Do you want me to start your Bike ?");
    builder.setContentTitle("Keyless Moto");
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);

    Notification notification = builder.build();
    nm.notify((int) System.currentTimeMillis(), notification);
}

}


person user3739891    schedule 04.07.2017    source источник


Ответы (1)


Эта строка, вероятно, неверна:

nm.notify((int) System.currentTimeMillis(), notification);

Используйте постоянный идентификатор:

nm.notify(12345, notification);

И отменить его при создании нового:

notificationManager.cancel(12345)
PushNotification(context);

Я также предлагаю вам эту ссылку для более эффективной фильтрации изменений ssid: available">Android WIFI Как определить, когда конкретное соединение WIFI доступно

person ben75    schedule 04.07.2017
comment
Спасибо за ваше решение :) - person user3739891; 04.07.2017