Java Code Examples for android.net.ConnectivityManager#registerNetworkCallback()
The following examples show how to use
android.net.ConnectivityManager#registerNetworkCallback() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequirementsWatcher.java From TelePlus-Android with GNU General Public License v2.0 | 7 votes |
@TargetApi(23) private void registerNetworkCallbackV23() { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest request = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build(); networkCallback = new CapabilityValidatedCallback(); connectivityManager.registerNetworkCallback(request, networkCallback); }
Example 2
Source File: FragmentOptionsConnection.java From FairEmail with GNU General Public License v3.0 | 7 votes |
@Override public void onResume() { super.onResume(); ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return; NetworkRequest.Builder builder = new NetworkRequest.Builder(); builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); cm.registerNetworkCallback(builder.build(), networkCallback); }
Example 3
Source File: SambaProviderApplication.java From samba-documents-provider with GNU General Public License v3.0 | 6 votes |
private void registerNetworkCallback(Context context) { final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); manager.registerNetworkCallback( new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET) .build(), new NetworkCallback() { @Override public void onAvailable(Network network) { mSambaClient.reset(); } }); }
Example 4
Source File: RequirementsWatcher.java From Telegram with GNU General Public License v2.0 | 5 votes |
@TargetApi(23) private void registerNetworkCallbackV23() { ConnectivityManager connectivityManager = Assertions.checkNotNull( (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); NetworkRequest request = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build(); networkCallback = new CapabilityValidatedCallback(); connectivityManager.registerNetworkCallback(request, networkCallback); }
Example 5
Source File: RequirementsWatcher.java From MediaSDK with Apache License 2.0 | 5 votes |
@TargetApi(23) private void registerNetworkCallbackV23() { ConnectivityManager connectivityManager = Assertions.checkNotNull( (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); NetworkRequest request = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build(); networkCallback = new CapabilityValidatedCallback(); connectivityManager.registerNetworkCallback(request, networkCallback); }
Example 6
Source File: FadeInNetworkImageView.java From QuickLyric with GNU General Public License v3.0 | 5 votes |
@TargetApi(21) @Override public void setImageUrl(String url, ImageLoader imageLoader) { mShowLocal = TextUtils.isEmpty(url); if (mDiskCache.get(url) == null && !OnlineAccessVerifier.check(getContext())) { this.setImageBitmap(null); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final ConnectivityManager cm = (ConnectivityManager) getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { super.onAvailable(network); new CoverArtLoader((MainActivity) FadeInNetworkImageView.this.getActivity()).execute(mLyrics); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && networkCallback != null) try { cm.unregisterNetworkCallback(networkCallback); } catch (IllegalArgumentException ignored) { } } }; NetworkRequest request = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); cm.registerNetworkCallback(request, networkCallback); } defaultShown = true; } else { super.setImageUrl(url, imageLoader); if (!TextUtils.isEmpty(url)) defaultShown = false; } }
Example 7
Source File: RequirementsWatcher.java From Telegram-FOSS with GNU General Public License v2.0 | 5 votes |
@TargetApi(23) private void registerNetworkCallbackV23() { ConnectivityManager connectivityManager = Assertions.checkNotNull( (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); NetworkRequest request = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build(); networkCallback = new CapabilityValidatedCallback(); connectivityManager.registerNetworkCallback(request, networkCallback); }
Example 8
Source File: AndroidDnsServer.java From happy-dns-android with MIT License | 5 votes |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) AndroidResolver(Context context){ networkCallback = false; List<InetAddress> addresses = getByReflection(); if (addresses == null) { addresses = getByCommand(); } if(addresses == null){ ///Android 8 , net.dns* was disabled, query dns servers must use network callback ///@see https://developer.android.com/about/versions/oreo/android-8.0-changes.html if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest.Builder builder = new NetworkRequest.Builder(); connectivityManager.registerNetworkCallback(builder.build(), new ConnectivityManager.NetworkCallback(){ @Override public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) { if(linkProperties != null) dnsServers.addAll(linkProperties.getDnsServers()); networkCallback = true; } }); } } else { dnsServers.addAll(addresses); } }
Example 9
Source File: ConnectivityNetworkCallback.java From unity-ads-android with Apache License 2.0 | 5 votes |
public static void register() { if(_impl == null) { _impl = new ConnectivityNetworkCallback(); ConnectivityManager cm = (ConnectivityManager) ClientProperties.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); cm.registerNetworkCallback(new NetworkRequest.Builder().build(), _impl); } }
Example 10
Source File: ConnectivityHelper.java From libcommon with Apache License 2.0 | 5 votes |
@SuppressLint("NewApi") @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) private void init() { if (DEBUG) Log.v(TAG, "init:"); final ConnectivityManager manager = requireConnectivityManager(); if (BuildCheck.isAPI21()) { mOnNetworkActiveListener = new MyOnNetworkActiveListener(); manager.addDefaultNetworkActiveListener(mOnNetworkActiveListener); // API>=21 mNetworkCallback = new MyNetworkCallback(); // ACCESS_NETWORK_STATEパーミッションが必要 if (BuildCheck.isAPI23()) { updateActiveNetwork(manager.getActiveNetwork()); // API>=23 if (BuildCheck.isAPI24()) { manager.registerDefaultNetworkCallback(mNetworkCallback); // API>=24 } else if (BuildCheck.isAPI26()) { manager.registerDefaultNetworkCallback(mNetworkCallback, mAsyncHandler); // API>=26 } } else { manager.registerNetworkCallback( new NetworkRequest.Builder().build(), mNetworkCallback); // API>=21 } } else { mNetworkChangedReceiver = new NetworkChangedReceiver(this); final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_GLOBAL_CONNECTIVITY_CHANGE); requireContext().registerReceiver(mNetworkChangedReceiver, intentFilter); } }
Example 11
Source File: TransmitterActivity.java From sample-lowpan with Apache License 2.0 | 5 votes |
/** * Initializes the network. */ private void resetNetwork() { // Initialize network onNoNetwork(); mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest networkRequest = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_LOWPAN) .build(); mBackgroundHandlerThread = new HandlerThread(TAG); mBackgroundHandlerThread.start(); mHandler = new Handler(mBackgroundHandlerThread.getLooper()); // Make sure that it is connected to a valid network mConnectivityManager.registerNetworkCallback(networkRequest, mNetworkCallback, mUiThreadHandler); }
Example 12
Source File: RequirementsWatcher.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
@TargetApi(23) private void registerNetworkCallbackV23() { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest request = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build(); networkCallback = new CapabilityValidatedCallback(); connectivityManager.registerNetworkCallback(request, networkCallback); }
Example 13
Source File: VideoDownloadManager.java From MediaSDK with Apache License 2.0 | 5 votes |
@SuppressLint("NewApi") @SuppressWarnings({"MissingPermission"}) private void registerConnectionListener(Context context) { NetworkCallbackImpl networkCallback = new NetworkCallbackImpl(mNetworkListener); NetworkRequest request = new NetworkRequest.Builder().build(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (manager != null) { manager.registerNetworkCallback(request, networkCallback); } }
Example 14
Source File: TindroidApp.java From tindroid with Apache License 2.0 | 4 votes |
@Override public void onCreate() { super.onCreate(); try { PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); sAppVersion = pi.versionName; sAppBuild = pi.versionCode; } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Failed to retrieve app version", e); } // Disable Crashlytics for debug builds. FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG); BroadcastReceiver br = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String token = intent.getStringExtra("token"); if (token != null && !token.equals("") && sTinodeCache != null) { sTinodeCache.setDeviceToken(token); } } }; LocalBroadcastManager.getInstance(this).registerReceiver(br, new IntentFilter("FCM_REFRESH_TOKEN")); createNotificationChannel(); ProcessLifecycleOwner.get().getLifecycle().addObserver(this); // Listen to connectivity changes. ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); if (cm == null) { return; } NetworkRequest req = new NetworkRequest. Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); cm.registerNetworkCallback(req, new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(@NonNull Network network) { super.onAvailable(network); if (sTinodeCache != null) { sTinodeCache.reconnectNow(true, false, false); } } }); // Check if preferences already exist. If not, create them. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); sServerHost = pref.getString("pref_hostName", null); if (TextUtils.isEmpty(sServerHost)) { // No preferences found. Save default values. SharedPreferences.Editor editor = pref.edit(); sServerHost = getDefaultHostName(this); sUseTLS = getDefaultTLS(); editor.putString("pref_hostName", sServerHost); editor.putBoolean("pref_useTLS", sUseTLS); editor.apply(); } else { sUseTLS = pref.getBoolean("pref_useTLS", false); } }
Example 15
Source File: ServiceSinkhole.java From NetGuard with GNU General Public License v3.0 | 4 votes |
@Override public void onCreate() { Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this)); startForeground(NOTIFY_WAITING, getWaitingNotification()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (jni_context != 0) { Log.w(TAG, "Create with context=" + jni_context); jni_stop(jni_context); synchronized (jni_lock) { jni_done(jni_context); jni_context = 0; } } // Native init jni_context = jni_init(Build.VERSION.SDK_INT); Log.i(TAG, "Created context=" + jni_context); boolean pcap = prefs.getBoolean("pcap", false); setPcap(pcap, this); prefs.registerOnSharedPreferenceChangeListener(this); Util.setTheme(this); super.onCreate(); HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command", Process.THREAD_PRIORITY_FOREGROUND); HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log", Process.THREAD_PRIORITY_BACKGROUND); HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats", Process.THREAD_PRIORITY_BACKGROUND); commandThread.start(); logThread.start(); statsThread.start(); commandLooper = commandThread.getLooper(); logLooper = logThread.getLooper(); statsLooper = statsThread.getLooper(); commandHandler = new CommandHandler(commandLooper); logHandler = new LogHandler(logLooper); statsHandler = new StatsHandler(statsLooper); // Listen for user switches if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { IntentFilter ifUser = new IntentFilter(); ifUser.addAction(Intent.ACTION_USER_BACKGROUND); ifUser.addAction(Intent.ACTION_USER_FOREGROUND); registerReceiver(userReceiver, ifUser); registeredUser = true; } // Listen for idle mode state changes if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { IntentFilter ifIdle = new IntentFilter(); ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED); registerReceiver(idleStateReceiver, ifIdle); registeredIdleState = true; } // Listen for added/removed applications IntentFilter ifPackage = new IntentFilter(); ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED); ifPackage.addAction(Intent.ACTION_PACKAGE_REMOVED); ifPackage.addDataScheme("package"); registerReceiver(packageChangedReceiver, ifPackage); registeredPackageChanged = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) try { listenNetworkChanges(); } catch (Throwable ex) { Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); listenConnectivityChanges(); } else listenConnectivityChanges(); // Monitor networks ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cm.registerNetworkCallback( new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), networkMonitorCallback); // Setup house holding Intent alarmIntent = new Intent(this, ServiceSinkhole.class); alarmIntent.setAction(ACTION_HOUSE_HOLDING); PendingIntent pi; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) pi = PendingIntent.getForegroundService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); else pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000, AlarmManager.INTERVAL_HALF_DAY, pi); }
Example 16
Source File: ServiceSend.java From FairEmail with GNU General Public License v3.0 | 4 votes |
@Override public void onCreate() { EntityLog.log(this, "Service send create"); super.onCreate(); startForeground(Helper.NOTIFICATION_SEND, getNotificationService().build()); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wlOutbox = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":send"); // Observe unsent count DB db = DB.getInstance(this); db.operation().liveUnsent().observe(this, new Observer<TupleUnsent>() { @Override public void onChanged(TupleUnsent unsent) { if (unsent == null || !unsent.equals(lastUnsent)) { lastUnsent = unsent; try { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(Helper.NOTIFICATION_SEND, getNotificationService().build()); } catch (Throwable ex) { Log.w(ex); } } } }); // Observe send operations db.operation().liveOperations(null).observe(owner, new Observer<List<TupleOperationEx>>() { @Override public void onChanged(List<TupleOperationEx> operations) { if (operations == null) operations = new ArrayList<>(); if (operations.size() == 0) stopSelf(); final List<TupleOperationEx> process = new ArrayList<>(); List<Long> ops = new ArrayList<>(); for (TupleOperationEx op : operations) { if (!handling.contains(op.id)) process.add(op); ops.add(op.id); } handling = ops; if (process.size() > 0) { Log.i("OUTBOX process=" + TextUtils.join(",", process) + " handling=" + TextUtils.join(",", handling)); executor.submit(new Runnable() { @Override public void run() { processOperations(process); } }); } } }); lastSuitable = ConnectionHelper.getNetworkState(this).isSuitable(); if (lastSuitable) owner.start(); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest.Builder builder = new NetworkRequest.Builder(); builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); cm.registerNetworkCallback(builder.build(), networkCallback); IntentFilter iif = new IntentFilter(); iif.addAction(ConnectivityManager.CONNECTIVITY_ACTION); iif.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); registerReceiver(connectionChangedReceiver, iif); }
Example 17
Source File: ServiceSinkhole.java From tracker-control-android with GNU General Public License v3.0 | 4 votes |
@Override public void onCreate() { Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this)); startForeground(NOTIFY_WAITING, getWaitingNotification()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (jni_context != 0) { Log.w(TAG, "Create with context=" + jni_context); jni_stop(jni_context); synchronized (jni_lock) { jni_done(jni_context); jni_context = 0; } } // Native init jni_context = jni_init(Build.VERSION.SDK_INT); Log.i(TAG, "Created context=" + jni_context); boolean pcap = prefs.getBoolean("pcap", false); setPcap(pcap, this); prefs.registerOnSharedPreferenceChangeListener(this); Util.setTheme(this); super.onCreate(); HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command", Process.THREAD_PRIORITY_FOREGROUND); HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log", Process.THREAD_PRIORITY_BACKGROUND); HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats", Process.THREAD_PRIORITY_BACKGROUND); commandThread.start(); logThread.start(); statsThread.start(); commandLooper = commandThread.getLooper(); logLooper = logThread.getLooper(); statsLooper = statsThread.getLooper(); commandHandler = new CommandHandler(commandLooper); logHandler = new LogHandler(logLooper); statsHandler = new StatsHandler(statsLooper); // Listen for user switches if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { IntentFilter ifUser = new IntentFilter(); ifUser.addAction(Intent.ACTION_USER_BACKGROUND); ifUser.addAction(Intent.ACTION_USER_FOREGROUND); registerReceiver(userReceiver, ifUser); registeredUser = true; } // Listen for idle mode state changes if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { IntentFilter ifIdle = new IntentFilter(); ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED); registerReceiver(idleStateReceiver, ifIdle); registeredIdleState = true; } // Listen for added/removed applications IntentFilter ifPackage = new IntentFilter(); ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED); ifPackage.addAction(Intent.ACTION_PACKAGE_REMOVED); ifPackage.addDataScheme("package"); registerReceiver(packageChangedReceiver, ifPackage); registeredPackageChanged = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) try { listenNetworkChanges(); } catch (Throwable ex) { Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); listenConnectivityChanges(); } else listenConnectivityChanges(); // Monitor networks ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cm.registerNetworkCallback( new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), networkMonitorCallback); // Setup house holding Intent alarmIntent = new Intent(this, ServiceSinkhole.class); alarmIntent.setAction(ACTION_HOUSE_HOLDING); PendingIntent pi; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) pi = PendingIntent.getForegroundService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); else pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000, AlarmManager.INTERVAL_HALF_DAY, pi); }