Made QKSMS open source

This commit is contained in:
Moez Bhatti
2015-08-16 12:02:49 -04:00
parent c664bbcbde
commit cc5e19575c
742 changed files with 135533 additions and 4 deletions
@@ -0,0 +1,37 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates a constant field value should be exported to be used in the SDK tools.
*
* @hide
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.SOURCE)
public @interface SdkConstant {
public static enum SdkConstantType {
ACTIVITY_INTENT_ACTION, BROADCAST_INTENT_ACTION, SERVICE_ACTION, INTENT_CATEGORY, FEATURE;
}
SdkConstantType value();
}
@@ -0,0 +1,110 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.database.sqlite;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
/**
* @hide
*/
public final class SqliteWrapper {
private static final String TAG = "SqliteWrapper";
private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE
= "unable to open database file";
private SqliteWrapper() {
// Forbidden being instantiated.
}
// FIXME: need to optimize this method.
private static boolean isLowMemory(SQLiteException e) {
return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE);
}
public static void checkSQLiteException(Context context, SQLiteException e) {
if (isLowMemory(e)) {
Toast.makeText(context, "Low Memory",
Toast.LENGTH_SHORT).show();
} else {
throw e;
}
}
public static Cursor query(Context context, ContentResolver resolver, Uri uri,
String[] projection, String selection, String[] selectionArgs, String sortOrder) {
try {
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when query: ", e);
checkSQLiteException(context, e);
return null;
}
}
@SuppressWarnings("deprecation")
public static boolean requery(Context context, Cursor cursor) {
try {
return cursor.requery();
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when requery: ", e);
checkSQLiteException(context, e);
return false;
}
}
public static int update(Context context, ContentResolver resolver, Uri uri,
ContentValues values, String where, String[] selectionArgs) {
try {
return resolver.update(uri, values, where, selectionArgs);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when update: ", e);
checkSQLiteException(context, e);
return -1;
}
}
public static int delete(Context context, ContentResolver resolver, Uri uri,
String where, String[] selectionArgs) {
try {
return resolver.delete(uri, where, selectionArgs);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when delete: ", e);
checkSQLiteException(context, e);
return -1;
}
}
public static Uri insert(Context context, ContentResolver resolver,
Uri uri, ContentValues values) {
try {
return resolver.insert(uri, values);
} catch (SQLiteException e) {
Log.e(TAG, "Catch a SQLiteException when insert: ", e);
checkSQLiteException(context, e);
return null;
}
}
}
@@ -0,0 +1,202 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package android.location;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import java.util.Locale;
/**
* This class wraps the country information.
*
* @hide
*/
public class Country implements Parcelable {
/**
* The country code came from the mobile network
*/
public static final int COUNTRY_SOURCE_NETWORK = 0;
/**
* The country code came from the location service
*/
public static final int COUNTRY_SOURCE_LOCATION = 1;
/**
* The country code was read from the SIM card
*/
public static final int COUNTRY_SOURCE_SIM = 2;
/**
* The country code came from the system locale setting
*/
public static final int COUNTRY_SOURCE_LOCALE = 3;
/**
* The ISO 3166-1 two letters country code.
*/
private final String mCountryIso;
/**
* Where the country code came from.
*/
private final int mSource;
private int mHashCode;
/**
* Time that this object was created (which we assume to be the time that the source was
* consulted). This time is in milliseconds since boot up.
*/
private final long mTimestamp;
/**
* @param countryIso the ISO 3166-1 two letters country code.
* @param source where the countryIso came from, could be one of below
* values
* <p>
* <ul>
* <li>{@link #COUNTRY_SOURCE_NETWORK}</li>
* <li>{@link #COUNTRY_SOURCE_LOCATION}</li>
* <li>{@link #COUNTRY_SOURCE_SIM}</li>
* <li>{@link #COUNTRY_SOURCE_LOCALE}</li>
* </ul>
*/
public Country(final String countryIso, final int source) {
if (countryIso == null || source < COUNTRY_SOURCE_NETWORK
|| source > COUNTRY_SOURCE_LOCALE) {
throw new IllegalArgumentException();
}
mCountryIso = countryIso.toUpperCase(Locale.US);
mSource = source;
mTimestamp = SystemClock.elapsedRealtime();
}
private Country(final String countryIso, final int source, long timestamp) {
if (countryIso == null || source < COUNTRY_SOURCE_NETWORK
|| source > COUNTRY_SOURCE_LOCALE) {
throw new IllegalArgumentException();
}
mCountryIso = countryIso.toUpperCase(Locale.US);
mSource = source;
mTimestamp = timestamp;
}
public Country(Country country) {
mCountryIso = country.mCountryIso;
mSource = country.mSource;
mTimestamp = country.mTimestamp;
}
/**
* @return the ISO 3166-1 two letters country code
*/
public final String getCountryIso() {
return mCountryIso;
}
/**
* @return where the country code came from, could be one of below values
* <p>
* <ul>
* <li>{@link #COUNTRY_SOURCE_NETWORK}</li>
* <li>{@link #COUNTRY_SOURCE_LOCATION}</li>
* <li>{@link #COUNTRY_SOURCE_SIM}</li>
* <li>{@link #COUNTRY_SOURCE_LOCALE}</li>
* </ul>
*/
public final int getSource() {
return mSource;
}
/**
* Returns the time that this object was created (which we assume to be the time that the source
* was consulted).
*/
public final long getTimestamp() {
return mTimestamp;
}
public static final Parcelable.Creator<Country> CREATOR = new Parcelable.Creator<Country>() {
public Country createFromParcel(Parcel in) {
return new Country(in.readString(), in.readInt(), in.readLong());
}
public Country[] newArray(int size) {
return new Country[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(mCountryIso);
parcel.writeInt(mSource);
parcel.writeLong(mTimestamp);
}
/**
* Returns true if this {@link Country} is equivalent to the given object. This ignores
* the timestamp value and just checks for equivalence of countryIso and source values.
* Returns false otherwise.
*/
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof Country) {
Country c = (Country) object;
// No need to check the equivalence of the timestamp
return mCountryIso.equals(c.getCountryIso()) && mSource == c.getSource();
}
return false;
}
@Override
public int hashCode() {
int hash = mHashCode;
if (hash == 0) {
hash = 17;
hash = hash * 13 + mCountryIso.hashCode();
hash = hash * 13 + mSource;
mHashCode = hash;
}
return mHashCode;
}
/**
* Compare the specified country to this country object ignoring the source
* and timestamp fields, return true if the countryIso fields are equal
*
* @param country the country to compare
* @return true if the specified country's countryIso field is equal to this
* country's, false otherwise.
*/
public boolean equalsIgnoreSource(Country country) {
return country != null && mCountryIso.equals(country.getCountryIso());
}
@Override
public String toString() {
return "Country {ISO=" + mCountryIso + ", source=" + mSource + ", time=" + mTimestamp + "}";
}
}
@@ -0,0 +1,137 @@
/*
* Copyright (C) 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
import android.os.Handler;
import android.os.Looper;
import java.util.HashMap;
/**
* This class provides access to the system country detector service. This
* service allows applications to obtain the country that the user is in.
* <p>
* The country will be detected in order of reliability, like
* <ul>
* <li>Mobile network</li>
* <li>Location</li>
* <li>SIM's country</li>
* <li>Phone's locale</li>
* </ul>
* <p>
* Call the {@link #detectCountry()} to get the available country immediately.
* <p>
* To be notified of the future country change, use the
* {@link #addCountryListener}
* <p>
* <p>
* You do not instantiate this class directly; instead, retrieve it through
* {@link android.content.Context#getSystemService
* Context.getSystemService(Context.COUNTRY_DETECTOR)}.
* <p>
* Both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions are needed.
*
* @hide
*/
public class CountryDetector {
/**
* The class to wrap the ICountryListener.Stub and CountryListener objects
* together. The CountryListener will be notified through the specific
* looper once the country changed and detected.
*/
private final static class ListenerTransport implements ICountryListener {
private final CountryListener mListener;
private final Handler mHandler;
public ListenerTransport(CountryListener listener, Looper looper) {
mListener = listener;
if (looper != null) {
mHandler = new Handler(looper);
} else {
mHandler = new Handler();
}
}
public void onCountryDetected(final Country country) {
mHandler.post(new Runnable() {
public void run() {
mListener.onCountryDetected(country);
}
});
}
}
private final static String TAG = "CountryDetector";
private final ICountryDetector mService;
private final HashMap<CountryListener, ListenerTransport> mListeners;
/**
* @hide - hide this constructor because it has a parameter of type
* ICountryDetector, which is a system private class. The right way to
* create an instance of this class is using the factory
* Context.getSystemService.
*/
public CountryDetector(ICountryDetector service) {
mService = service;
mListeners = new HashMap<CountryListener, ListenerTransport>();
}
/**
* Start detecting the country that the user is in.
*
* @return the country if it is available immediately, otherwise null will
* be returned.
*/
public Country detectCountry() {
return mService.detectCountry();
}
/**
* Add a listener to receive the notification when the country is detected
* or changed.
*
* @param listener will be called when the country is detected or changed.
* @param looper a Looper object whose message queue will be used to
* implement the callback mechanism. If looper is null then the
* callbacks will be called on the main thread.
*/
public void addCountryListener(CountryListener listener, Looper looper) {
synchronized (mListeners) {
if (!mListeners.containsKey(listener)) {
ListenerTransport transport = new ListenerTransport(listener, looper);
mService.addCountryListener(transport);
mListeners.put(listener, transport);
}
}
}
/**
* Remove the listener
*/
public void removeCountryListener(CountryListener listener) {
synchronized (mListeners) {
ListenerTransport transport = mListeners.get(listener);
if (transport != null) {
mListeners.remove(listener);
mService.removeCountryListener(transport);
}
}
}
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package android.location;
/**
* The listener for receiving the notification when the country is detected or
* changed
*
* @hide
*/
public interface CountryListener {
/**
* @param country the changed or detected country.
*/
void onCountryDetected(Country country);
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
/**
* The API for detecting the country where the user is.
*
* {@hide}
*/
interface ICountryDetector
{
/**
* Start detecting the country that the user is in.
* @return the country if it is available immediately, otherwise null will be returned.
*/
Country detectCountry();
/**
* Add a listener to receive the notification when the country is detected or changed.
*/
void addCountryListener(ICountryListener listener);
/**
* Remove the listener
*/
void removeCountryListener(ICountryListener listener);
}
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
/**
* {@hide}
*/
interface ICountryListener
{
void onCountryDetected(Country country);
}
@@ -0,0 +1,992 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.content.Context;
import android.os.Binder;
import android.os.Build.VERSION_CODES;
import android.os.RemoteException;
import android.provider.Settings;
import java.net.InetAddress;
import static com.android.internal.util.Preconditions.checkNotNull;
/**
* Class that answers queries about the state of network connectivity. It also
* notifies applications when network connectivity changes. Get an instance
* of this class by calling
* {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
* <p/>
* The primary responsibilities of this class are to:
* <ol>
* <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
* <li>Send broadcast intents when network connectivity changes</li>
* <li>Attempt to "fail over" to another network when connectivity to a network
* is lost</li>
* <li>Provide an API that allows applications to query the coarse-grained or fine-grained
* state of the available networks</li>
* </ol>
*/
public class ConnectivityManager {
/**
* A change in network connectivity has occurred. A connection has either
* been established or lost. The NetworkInfo for the affected network is
* sent as an extra; it should be consulted to see what kind of
* connectivity event occurred.
* <p/>
* If this is a connection that was the result of failing over from a
* disconnected network, then the FAILOVER_CONNECTION boolean extra is
* set to true.
* <p/>
* For a loss of connectivity, if the connectivity manager is attempting
* to connect (or has already connected) to another network, the
* NetworkInfo for the new network is also passed as an extra. This lets
* any receivers of the broadcast know that they should not necessarily
* tell the user that no data traffic will be possible. Instead, the
* reciever should expect another broadcast soon, indicating either that
* the failover attempt succeeded (and so there is still overall data
* connectivity), or that the failover attempt failed, meaning that all
* connectivity has been lost.
* <p/>
* For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
* is set to {@code true} if there are no connected networks at all.
*/
public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
/**
* Identical to {@link #CONNECTIVITY_ACTION} broadcast, but sent without any
* applicable {@link Settings.Secure#CONNECTIVITY_CHANGE_DELAY}.
*
* @hide
*/
public static final String CONNECTIVITY_ACTION_IMMEDIATE =
"android.net.conn.CONNECTIVITY_CHANGE_IMMEDIATE";
/**
* The lookup key for a {@link NetworkInfo} object. Retrieve with
* {@link android.content.Intent#getParcelableExtra(String)}.
*
* @see #EXTRA_NETWORK_TYPE
* @deprecated Since {@link NetworkInfo} can vary based on UID, applications
* should always obtain network information through
* {@link #getActiveNetworkInfo()} or
* {@link #getAllNetworkInfo()}.
*/
@Deprecated
public static final String EXTRA_NETWORK_INFO = "networkInfo";
/**
* Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
* Can be used with {@link #getNetworkInfo(int)} to get {@link NetworkInfo}
* state based on the calling application.
*
* @see android.content.Intent#getIntExtra(String, int)
*/
public static final String EXTRA_NETWORK_TYPE = "networkType";
/**
* The lookup key for a boolean that indicates whether a connect event
* is for a network to which the connectivity manager was failing over
* following a disconnect on another network.
* Retrieve it with {@link android.content.Intent#getBooleanExtra(String, boolean)}.
*/
public static final String EXTRA_IS_FAILOVER = "isFailover";
/**
* The lookup key for a {@link NetworkInfo} object. This is supplied when
* there is another network that it may be possible to connect to. Retrieve with
* {@link android.content.Intent#getParcelableExtra(String)}.
*/
public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
/**
* The lookup key for a boolean that indicates whether there is a
* complete lack of connectivity, i.e., no network is available.
* Retrieve it with {@link android.content.Intent#getBooleanExtra(String, boolean)}.
*/
public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
/**
* The lookup key for a string that indicates why an attempt to connect
* to a network failed. The string has no particular structure. It is
* intended to be used in notifications presented to users. Retrieve
* it with {@link android.content.Intent#getStringExtra(String)}.
*/
public static final String EXTRA_REASON = "reason";
/**
* The lookup key for a string that provides optionally supplied
* extra information about the network state. The information
* may be passed up from the lower networking layers, and its
* meaning may be specific to a particular network type. Retrieve
* it with {@link android.content.Intent#getStringExtra(String)}.
*/
public static final String EXTRA_EXTRA_INFO = "extraInfo";
/**
* The lookup key for an int that provides information about
* our connection to the internet at large. 0 indicates no connection,
* 100 indicates a great connection. Retrieve it with
* {@link android.content.Intent#getIntExtra(String, int)}.
* {@hide}
*/
public static final String EXTRA_INET_CONDITION = "inetCondition";
/**
* Broadcast action to indicate the change of data activity status
* (idle or active) on a network in a recent period.
* The network becomes active when data transimission is started, or
* idle if there is no data transimition for a period of time.
* {@hide}
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE";
/**
* The lookup key for an enum that indicates the network device type on which this data activity
* change happens.
* {@hide}
*/
public static final String EXTRA_DEVICE_TYPE = "deviceType";
/**
* The lookup key for a boolean that indicates the device is active or not. {@code true} means
* it is actively sending or receiving data and {@code false} means it is idle.
* {@hide}
*/
public static final String EXTRA_IS_ACTIVE = "isActive";
/**
* Broadcast Action: The setting for background data usage has changed
* values. Use {@link #getBackgroundDataSetting()} to get the current value.
* <p/>
* If an application uses the network in the background, it should listen
* for this broadcast and stop using the background data if the value is
* {@code false}.
* <p/>
*
* @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
* of background data depends on several combined factors, and
* this broadcast is no longer sent. Instead, when background
* data is unavailable, {@link #getActiveNetworkInfo()} will now
* appear disconnected. During first boot after a platform
* upgrade, this broadcast will be sent once if
* {@link #getBackgroundDataSetting()} was {@code false} before
* the upgrade.
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
@Deprecated
public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
"android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
/**
* Broadcast Action: The network connection may not be good
* uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
* {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
* the network and it's condition.
*
* @hide
*/
public static final String INET_CONDITION_ACTION =
"android.net.conn.INET_CONDITION_ACTION";
/**
* Broadcast Action: A tetherable connection has come or gone
* TODO - finish the doc
*
* @hide
*/
public static final String ACTION_TETHER_STATE_CHANGED =
"android.net.conn.TETHER_STATE_CHANGED";
/**
* @hide gives a String[]
*/
public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
/**
* @hide gives a String[]
*/
public static final String EXTRA_ACTIVE_TETHER = "activeArray";
/**
* @hide gives a String[]
*/
public static final String EXTRA_ERRORED_TETHER = "erroredArray";
/**
* The absence of APN..
*
* @hide
*/
public static final int TYPE_NONE = -1;
/**
* The Default Mobile data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_MOBILE = 0;
/**
* The Default WIFI data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_WIFI = 1;
/**
* An MMS-specific Mobile data connection. This connection may be the
* same as {@link #TYPE_MOBILE} but it may be different. This is used
* by applications needing to talk to the carrier's Multimedia Messaging
* Service servers. It may coexist with default data connections.
*/
public static final int TYPE_MOBILE_MMS = 2;
/**
* A SUPL-specific Mobile data connection. This connection may be the
* same as {@link #TYPE_MOBILE} but it may be different. This is used
* by applications needing to talk to the carrier's Secure User Plane
* Location servers for help locating the device. It may coexist with
* default data connections.
*/
public static final int TYPE_MOBILE_SUPL = 3;
/**
* A DUN-specific Mobile data connection. This connection may be the
* same as {@link #TYPE_MOBILE} but it may be different. This is used
* by applicaitons performing a Dial Up Networking bridge so that
* the carrier is aware of DUN traffic. It may coexist with default data
* connections.
*/
public static final int TYPE_MOBILE_DUN = 4;
/**
* A High Priority Mobile data connection. This connection is typically
* the same as {@link #TYPE_MOBILE} but the routing setup is different.
* Only requesting processes will have access to the Mobile DNS servers
* and only IP's explicitly requested via {@link #requestRouteToHost}
* will route over this interface if a default route exists.
*/
public static final int TYPE_MOBILE_HIPRI = 5;
/**
* The Default WiMAX data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_WIMAX = 6;
/**
* The Default Bluetooth data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_BLUETOOTH = 7;
/**
* Dummy data connection. This should not be used on shipping devices.
*/
public static final int TYPE_DUMMY = 8;
/**
* The Default Ethernet data connection. When active, all data traffic
* will use this connection by default.
*/
public static final int TYPE_ETHERNET = 9;
/**
* Over the air Adminstration.
* {@hide}
*/
public static final int TYPE_MOBILE_FOTA = 10;
/**
* IP Multimedia Subsystem
* {@hide}
*/
public static final int TYPE_MOBILE_IMS = 11;
/**
* Carrier Branded Services
* {@hide}
*/
public static final int TYPE_MOBILE_CBS = 12;
/**
* A Wi-Fi p2p connection. Only requesting processes will have access to
* the peers connected.
* {@hide}
*/
public static final int TYPE_WIFI_P2P = 13;
/**
* {@hide}
*/
public static final int MAX_RADIO_TYPE = TYPE_WIFI_P2P;
/**
* {@hide}
*/
public static final int MAX_NETWORK_TYPE = TYPE_WIFI_P2P;
public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
/**
* Default value for {@link Settings.Global#CONNECTIVITY_CHANGE_DELAY} in
* milliseconds.
*
* @hide
*/
public static final int CONNECTIVITY_CHANGE_DELAY_DEFAULT = 3000;
private final IConnectivityManager mService;
public static boolean isNetworkTypeValid(int networkType) {
return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
}
/**
* {@hide}
*/
public static String getNetworkTypeName(int type) {
switch (type) {
case TYPE_MOBILE:
return "MOBILE";
case TYPE_WIFI:
return "WIFI";
case TYPE_MOBILE_MMS:
return "MOBILE_MMS";
case TYPE_MOBILE_SUPL:
return "MOBILE_SUPL";
case TYPE_MOBILE_DUN:
return "MOBILE_DUN";
case TYPE_MOBILE_HIPRI:
return "MOBILE_HIPRI";
case TYPE_WIMAX:
return "WIMAX";
case TYPE_BLUETOOTH:
return "BLUETOOTH";
case TYPE_DUMMY:
return "DUMMY";
case TYPE_ETHERNET:
return "ETHERNET";
case TYPE_MOBILE_FOTA:
return "MOBILE_FOTA";
case TYPE_MOBILE_IMS:
return "MOBILE_IMS";
case TYPE_MOBILE_CBS:
return "MOBILE_CBS";
case TYPE_WIFI_P2P:
return "WIFI_P2P";
default:
return Integer.toString(type);
}
}
/**
* {@hide}
*/
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case TYPE_MOBILE:
case TYPE_MOBILE_MMS:
case TYPE_MOBILE_SUPL:
case TYPE_MOBILE_DUN:
case TYPE_MOBILE_HIPRI:
case TYPE_MOBILE_FOTA:
case TYPE_MOBILE_IMS:
case TYPE_MOBILE_CBS:
return true;
default:
return false;
}
}
public void setNetworkPreference(int preference) {
try {
mService.setNetworkPreference(preference);
} catch (RemoteException e) {
}
}
public int getNetworkPreference() {
try {
return mService.getNetworkPreference();
} catch (RemoteException e) {
return -1;
}
}
/**
* Returns details about the currently active data network. When connected,
* this network is the default route for outgoing connections. You should
* always check {@link NetworkInfo#isConnected()} before initiating network
* traffic. This may return {@code null} when no networks are available.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
*/
public NetworkInfo getActiveNetworkInfo() {
try {
return mService.getActiveNetworkInfo();
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public NetworkInfo getActiveNetworkInfoForUid(int uid) {
try {
return mService.getActiveNetworkInfoForUid(uid);
} catch (RemoteException e) {
return null;
}
}
public NetworkInfo getNetworkInfo(int networkType) {
try {
return mService.getNetworkInfo(networkType);
} catch (RemoteException e) {
return null;
}
}
public NetworkInfo[] getAllNetworkInfo() {
try {
return mService.getAllNetworkInfo();
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public LinkProperties getActiveLinkProperties() {
try {
return mService.getActiveLinkProperties();
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public LinkProperties getLinkProperties(int networkType) {
try {
return mService.getLinkProperties(networkType);
} catch (RemoteException e) {
return null;
}
}
/**
* {@hide}
*/
public boolean setRadios(boolean turnOn) {
try {
return mService.setRadios(turnOn);
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public boolean setRadio(int networkType, boolean turnOn) {
try {
return mService.setRadio(networkType, turnOn);
} catch (RemoteException e) {
return false;
}
}
/**
* Tells the underlying networking system that the caller wants to
* begin using the named feature. The interpretation of {@code feature}
* is completely up to each networking implementation.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
*
* @param networkType specifies which network the request pertains to
* @param feature the name of the feature to be used
* @return an integer value representing the outcome of the request.
* The interpretation of this value is specific to each networking
* implementation+feature combination, except that the value {@code -1}
* always indicates failure.
*/
public int startUsingNetworkFeature(int networkType, String feature) {
try {
return mService.startUsingNetworkFeature(networkType, feature,
new Binder());
} catch (RemoteException e) {
return -1;
}
}
/**
* Tells the underlying networking system that the caller is finished
* using the named feature. The interpretation of {@code feature}
* is completely up to each networking implementation.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
*
* @param networkType specifies which network the request pertains to
* @param feature the name of the feature that is no longer needed
* @return an integer value representing the outcome of the request.
* The interpretation of this value is specific to each networking
* implementation+feature combination, except that the value {@code -1}
* always indicates failure.
*/
public int stopUsingNetworkFeature(int networkType, String feature) {
try {
return mService.stopUsingNetworkFeature(networkType, feature);
} catch (RemoteException e) {
return -1;
}
}
/**
* Ensure that a network route exists to deliver traffic to the specified
* host via the specified network interface. An attempt to add a route that
* already exists is ignored, but treated as successful.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
*
* @param networkType the type of the network over which traffic to the specified
* host is to be routed
* @param hostAddress the IP address of the host to which the route is desired
* @return {@code true} on success, {@code false} on failure
*/
public boolean requestRouteToHost(int networkType, int hostAddress) {
InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
if (inetAddress == null) {
return false;
}
return requestRouteToHostAddress(networkType, inetAddress);
}
/**
* Ensure that a network route exists to deliver traffic to the specified
* host via the specified network interface. An attempt to add a route that
* already exists is ignored, but treated as successful.
*
* @param networkType the type of the network over which traffic to the specified
* host is to be routed
* @param hostAddress the IP address of the host to which the route is desired
* @return {@code true} on success, {@code false} on failure
* @hide
*/
public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
byte[] address = hostAddress.getAddress();
try {
return mService.requestRouteToHostAddress(networkType, address);
} catch (RemoteException e) {
return false;
}
}
/**
* Returns the value of the setting for background data usage. If false,
* applications should not use the network if the application is not in the
* foreground. Developers should respect this setting, and check the value
* of this before performing any background data operations.
* <p/>
* All applications that have background services that use the network
* should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
* <p/>
*
* @return Whether background data usage is allowed.
* @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
* background data depends on several combined factors, and this method will
* always return {@code true}. Instead, when background data is unavailable,
* {@link #getActiveNetworkInfo()} will now appear disconnected.
*/
@Deprecated
public boolean getBackgroundDataSetting() {
// assume that background data is allowed; final authority is
// NetworkInfo which may be blocked.
return true;
}
/**
* Sets the value of the setting for background data usage.
*
* @param allowBackgroundData Whether an application should use data while
* it is in the background.
* @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
* @hide
* @see #getBackgroundDataSetting()
*/
@Deprecated
public void setBackgroundDataSetting(boolean allowBackgroundData) {
// ignored
}
/**
* Return quota status for the current active network, or {@code null} if no
* network is active. Quota status can change rapidly, so these values
* shouldn't be cached.
*
* @hide
*/
public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
try {
return mService.getActiveNetworkQuotaInfo();
} catch (RemoteException e) {
return null;
}
}
/**
* Gets the value of the setting for enabling Mobile data.
*
* @return Whether mobile data is enabled.
* @hide
*/
public boolean getMobileDataEnabled() {
try {
return mService.getMobileDataEnabled();
} catch (RemoteException e) {
return true;
}
}
/**
* Sets the persisted value for enabling/disabling Mobile data.
*
* @param enabled Whether the mobile data connection should be
* used or not.
* @hide
*/
public void setMobileDataEnabled(boolean enabled) {
try {
mService.setMobileDataEnabled(enabled);
} catch (RemoteException e) {
}
}
/**
* {@hide}
*/
public ConnectivityManager(IConnectivityManager service) {
mService = checkNotNull(service, "missing IConnectivityManager");
}
/**
* {@hide}
*/
public static ConnectivityManager from(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* {@hide}
*/
public String[] getTetherableIfaces() {
try {
return mService.getTetherableIfaces();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetheredIfaces() {
try {
return mService.getTetheredIfaces();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetheringErroredIfaces() {
try {
return mService.getTetheringErroredIfaces();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* @return error A TETHER_ERROR value indicating success or failure type
* {@hide}
*/
public int tether(String iface) {
try {
return mService.tether(iface);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* @return error A TETHER_ERROR value indicating success or failure type
* {@hide}
*/
public int untether(String iface) {
try {
return mService.untether(iface);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* {@hide}
*/
public boolean isTetheringSupported() {
try {
return mService.isTetheringSupported();
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public String[] getTetherableUsbRegexs() {
try {
return mService.getTetherableUsbRegexs();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetherableWifiRegexs() {
try {
return mService.getTetherableWifiRegexs();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public String[] getTetherableBluetoothRegexs() {
try {
return mService.getTetherableBluetoothRegexs();
} catch (RemoteException e) {
return new String[0];
}
}
/**
* {@hide}
*/
public int setUsbTethering(boolean enable) {
try {
return mService.setUsbTethering(enable);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* {@hide}
*/
public static final int TETHER_ERROR_NO_ERROR = 0;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
/**
* {@hide}
*/
public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNSUPPORTED = 3;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
/**
* {@hide}
*/
public static final int TETHER_ERROR_MASTER_ERROR = 5;
/**
* {@hide}
*/
public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
/**
* {@hide}
*/
public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
/**
* {@hide}
*/
public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
/**
* {@hide}
*/
public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
/**
* {@hide}
*/
public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
/**
* @param iface The name of the interface we're interested in
* @return error The error code of the last error tethering or untethering the named
* interface
* {@hide}
*/
public int getLastTetherError(String iface) {
try {
return mService.getLastTetherError(iface);
} catch (RemoteException e) {
return TETHER_ERROR_SERVICE_UNAVAIL;
}
}
/**
* Ensure the device stays awake until we connect with the next network
*
* @param forWhome The name of the network going down for logging purposes
* @return {@code true} on success, {@code false} on failure
* {@hide}
*/
public boolean requestNetworkTransitionWakelock(String forWhom) {
try {
mService.requestNetworkTransitionWakelock(forWhom);
return true;
} catch (RemoteException e) {
return false;
}
}
/**
* @param networkType The type of network you want to report on
* @param percentage The quality of the connection 0 is bad, 100 is good
* {@hide}
*/
public void reportInetCondition(int networkType, int percentage) {
try {
mService.reportInetCondition(networkType, percentage);
} catch (RemoteException e) {
}
}
/**
* @param proxyProperties The definition for the new global http proxy
* {@hide}
*/
public void setGlobalProxy(ProxyProperties p) {
try {
mService.setGlobalProxy(p);
} catch (RemoteException e) {
}
}
/**
* @return proxyProperties for the current global proxy
* {@hide}
*/
public ProxyProperties getGlobalProxy() {
try {
return mService.getGlobalProxy();
} catch (RemoteException e) {
return null;
}
}
/**
* @return proxyProperties for the current proxy (global if set, network specific if not)
* {@hide}
*/
public ProxyProperties getProxy() {
try {
return mService.getProxy();
} catch (RemoteException e) {
return null;
}
}
/**
* @param networkType The network who's dependence has changed
* @param met Boolean - true if network use is ok, false if not
* {@hide}
*/
public void setDataDependency(int networkType, boolean met) {
try {
mService.setDataDependency(networkType, met);
} catch (RemoteException e) {
}
}
/**
* Returns true if the hardware supports the given network type
* else it returns false. This doesn't indicate we have coverage
* or are authorized onto a network, just whether or not the
* hardware supports it. For example a gsm phone without a sim
* should still return true for mobile data, but a wifi only tablet
* would return false.
*
* @param networkType The nework type we'd like to check
* @return true if supported, else false
* @hide
*/
public boolean isNetworkSupported(int networkType) {
try {
return mService.isNetworkSupported(networkType);
} catch (RemoteException e) {
}
return false;
}
/**
* Returns if the currently active data network is metered. A network is
* classified as metered when the user is sensitive to heavy data usage on
* that connection. You should check this before doing large data transfers,
* and warn the user or delay the operation until another network is
* available.
*/
public boolean isActiveNetworkMetered() {
try {
return mService.isActiveNetworkMetered();
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public boolean updateLockdownVpn() {
try {
return mService.updateLockdownVpn();
} catch (RemoteException e) {
return false;
}
}
/**
* {@hide}
*/
public void captivePortalCheckComplete(NetworkInfo info) {
try {
mService.captivePortalCheckComplete(info);
} catch (RemoteException e) {
}
}
}
@@ -0,0 +1,171 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.text.TextUtils;
import android.util.Log;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* A simple object for retrieving the results of a DHCP request.
* Replaces (internally) the IPv4-only DhcpInfo class.
*
* @hide
*/
public class DhcpInfoInternal {
private final static String TAG = "DhcpInfoInternal";
private final static boolean LOCAL_LOGV = false;
public String ipAddress;
public int prefixLength;
public String dns1;
public String dns2;
public String serverAddress;
public int leaseDuration;
/**
* Vendor specific information (from RFC 2132).
*/
public String vendorInfo;
private Collection<RouteInfo> mRoutes;
public DhcpInfoInternal() {
mRoutes = new ArrayList<RouteInfo>();
}
public void addRoute(RouteInfo routeInfo) {
mRoutes.add(routeInfo);
}
public Collection<RouteInfo> getRoutes() {
return Collections.unmodifiableCollection(mRoutes);
}
private int convertToInt(String addr) {
if (addr != null) {
try {
InetAddress inetAddress = NetworkUtils.numericToInetAddress(addr);
if (inetAddress instanceof Inet4Address) {
return NetworkUtils.inetAddressToInt(inetAddress);
}
} catch (IllegalArgumentException e) {
}
}
return 0;
}
public DhcpInfo makeDhcpInfo() {
DhcpInfo info = new DhcpInfo();
info.ipAddress = convertToInt(ipAddress);
for (RouteInfo route : mRoutes) {
if (route.isDefaultRoute()) {
info.gateway = convertToInt(route.getGateway().getHostAddress());
break;
}
}
try {
info.netmask = NetworkUtils.prefixLengthToNetmaskInt(prefixLength);
} catch (IllegalArgumentException e) {
}
info.dns1 = convertToInt(dns1);
info.dns2 = convertToInt(dns2);
info.serverAddress = convertToInt(serverAddress);
info.leaseDuration = leaseDuration;
return info;
}
public LinkAddress makeLinkAddress() {
if (TextUtils.isEmpty(ipAddress)) {
Log.e(TAG, "makeLinkAddress with empty ipAddress");
return null;
}
return new LinkAddress(NetworkUtils.numericToInetAddress(ipAddress), prefixLength);
}
public LinkProperties makeLinkProperties() {
LinkProperties p = new LinkProperties();
p.addLinkAddress(makeLinkAddress());
for (RouteInfo route : mRoutes) {
p.addRoute(route);
}
//if empty, connectivity configures default DNS
if (TextUtils.isEmpty(dns1) == false) {
p.addDns(NetworkUtils.numericToInetAddress(dns1));
} else {
if (LOCAL_LOGV) Log.v(TAG, "makeLinkProperties with empty dns1!");
}
if (TextUtils.isEmpty(dns2) == false) {
p.addDns(NetworkUtils.numericToInetAddress(dns2));
} else {
if (LOCAL_LOGV) Log.v(TAG, "makeLinkProperties with empty dns2!");
}
return p;
}
/* Updates the DHCP fields that need to be retained from
* original DHCP request if the DHCP renewal shows them as
* being empty
*/
public void updateFromDhcpRequest(DhcpInfoInternal orig) {
if (orig == null) return;
if (TextUtils.isEmpty(dns1)) {
dns1 = orig.dns1;
}
if (TextUtils.isEmpty(dns2)) {
dns2 = orig.dns2;
}
if (mRoutes.size() == 0) {
for (RouteInfo route : orig.getRoutes()) {
addRoute(route);
}
}
}
/**
* Test if this DHCP lease includes vendor hint that network link is
* metered, and sensitive to heavy data transfers.
*/
public boolean hasMeteredHint() {
if (vendorInfo != null) {
return vendorInfo.contains("ANDROID_METERED");
} else {
return false;
}
}
public String toString() {
String routeString = "";
for (RouteInfo route : mRoutes) routeString += route.toString() + " | ";
return "addr: " + ipAddress + "/" + prefixLength +
" mRoutes: " + routeString +
" dns: " + dns1 + "," + dns2 +
" dhcpServer: " + serverAddress +
" leaseDuration: " + leaseDuration;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,138 @@
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: frameworks/base/core/java/android/net/INetworkPolicyListener.aidl
*/
package android.net;
/**
* {@hide}
*/
public interface INetworkPolicyListener extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public static abstract class Stub extends android.os.Binder implements android.net.INetworkPolicyListener {
private static final String DESCRIPTOR = "android.net.INetworkPolicyListener";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.net.INetworkPolicyListener interface,
* generating a proxy if needed.
*/
public static android.net.INetworkPolicyListener asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof android.net.INetworkPolicyListener))) {
return ((android.net.INetworkPolicyListener) iin);
}
return new android.net.INetworkPolicyListener.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_onUidRulesChanged: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
this.onUidRulesChanged(_arg0, _arg1);
return true;
}
case TRANSACTION_onMeteredIfacesChanged: {
data.enforceInterface(DESCRIPTOR);
String[] _arg0;
_arg0 = data.createStringArray();
this.onMeteredIfacesChanged(_arg0);
return true;
}
case TRANSACTION_onRestrictBackgroundChanged: {
data.enforceInterface(DESCRIPTOR);
boolean _arg0;
_arg0 = (0 != data.readInt());
this.onRestrictBackgroundChanged(_arg0);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.net.INetworkPolicyListener {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
@Override
public void onUidRulesChanged(int uid, int uidRules) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
_data.writeInt(uidRules);
mRemote.transact(Stub.TRANSACTION_onUidRulesChanged, _data, null, android.os.IBinder.FLAG_ONEWAY);
} finally {
_data.recycle();
}
}
@Override
public void onMeteredIfacesChanged(String[] meteredIfaces) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStringArray(meteredIfaces);
mRemote.transact(Stub.TRANSACTION_onMeteredIfacesChanged, _data, null, android.os.IBinder.FLAG_ONEWAY);
} finally {
_data.recycle();
}
}
@Override
public void onRestrictBackgroundChanged(boolean restrictBackground) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(((restrictBackground) ? (1) : (0)));
mRemote.transact(Stub.TRANSACTION_onRestrictBackgroundChanged, _data, null, android.os.IBinder.FLAG_ONEWAY);
} finally {
_data.recycle();
}
}
}
static final int TRANSACTION_onUidRulesChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_onMeteredIfacesChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_onRestrictBackgroundChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
}
public void onUidRulesChanged(int uid, int uidRules) throws android.os.RemoteException;
public void onMeteredIfacesChanged(String[] meteredIfaces) throws android.os.RemoteException;
public void onRestrictBackgroundChanged(boolean restrictBackground) throws android.os.RemoteException;
}
@@ -0,0 +1,494 @@
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: frameworks/base/core/java/android/net/INetworkPolicyManager.aidl
*/
package android.net;
/**
* Interface that creates and modifies network policy rules.
* <p/>
* {@hide}
*/
public interface INetworkPolicyManager extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public static abstract class Stub extends android.os.Binder implements android.net.INetworkPolicyManager {
private static final String DESCRIPTOR = "android.net.INetworkPolicyManager";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.net.INetworkPolicyManager interface,
* generating a proxy if needed.
*/
public static android.net.INetworkPolicyManager asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof android.net.INetworkPolicyManager))) {
return ((android.net.INetworkPolicyManager) iin);
}
return new android.net.INetworkPolicyManager.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_setUidPolicy: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
this.setUidPolicy(_arg0, _arg1);
reply.writeNoException();
return true;
}
case TRANSACTION_getUidPolicy: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _result = this.getUidPolicy(_arg0);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_getUidsWithPolicy: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int[] _result = this.getUidsWithPolicy(_arg0);
reply.writeNoException();
reply.writeIntArray(_result);
return true;
}
case TRANSACTION_isUidForeground: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
boolean _result = this.isUidForeground(_arg0);
reply.writeNoException();
reply.writeInt(((_result) ? (1) : (0)));
return true;
}
case TRANSACTION_registerListener: {
data.enforceInterface(DESCRIPTOR);
android.net.INetworkPolicyListener _arg0;
_arg0 = android.net.INetworkPolicyListener.Stub.asInterface(data.readStrongBinder());
this.registerListener(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_unregisterListener: {
data.enforceInterface(DESCRIPTOR);
android.net.INetworkPolicyListener _arg0;
_arg0 = android.net.INetworkPolicyListener.Stub.asInterface(data.readStrongBinder());
this.unregisterListener(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_setNetworkPolicies: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkPolicy[] _arg0;
_arg0 = data.createTypedArray(android.net.NetworkPolicy.CREATOR);
this.setNetworkPolicies(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_getNetworkPolicies: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkPolicy[] _result = this.getNetworkPolicies();
reply.writeNoException();
reply.writeTypedArray(_result, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
return true;
}
case TRANSACTION_snoozeLimit: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkTemplate _arg0;
if ((0 != data.readInt())) {
_arg0 = android.net.NetworkTemplate.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
this.snoozeLimit(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_setRestrictBackground: {
data.enforceInterface(DESCRIPTOR);
boolean _arg0;
_arg0 = (0 != data.readInt());
this.setRestrictBackground(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_getRestrictBackground: {
data.enforceInterface(DESCRIPTOR);
boolean _result = this.getRestrictBackground();
reply.writeNoException();
reply.writeInt(((_result) ? (1) : (0)));
return true;
}
case TRANSACTION_getNetworkQuotaInfo: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkState _arg0;
if ((0 != data.readInt())) {
_arg0 = android.net.NetworkState.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
android.net.NetworkQuotaInfo _result = this.getNetworkQuotaInfo(_arg0);
reply.writeNoException();
if ((_result != null)) {
reply.writeInt(1);
_result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
reply.writeInt(0);
}
return true;
}
case TRANSACTION_isNetworkMetered: {
data.enforceInterface(DESCRIPTOR);
android.net.NetworkState _arg0;
if ((0 != data.readInt())) {
_arg0 = android.net.NetworkState.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
boolean _result = this.isNetworkMetered(_arg0);
reply.writeNoException();
reply.writeInt(((_result) ? (1) : (0)));
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.net.INetworkPolicyManager {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
/**
* Control UID policies.
*/
@Override
public void setUidPolicy(int uid, int policy) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
_data.writeInt(policy);
mRemote.transact(Stub.TRANSACTION_setUidPolicy, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public int getUidPolicy(int uid) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
mRemote.transact(Stub.TRANSACTION_getUidPolicy, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public int[] getUidsWithPolicy(int policy) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int[] _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(policy);
mRemote.transact(Stub.TRANSACTION_getUidsWithPolicy, _data, _reply, 0);
_reply.readException();
_result = _reply.createIntArray();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public boolean isUidForeground(int uid) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
mRemote.transact(Stub.TRANSACTION_isUidForeground, _data, _reply, 0);
_reply.readException();
_result = (0 != _reply.readInt());
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public void registerListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((((listener != null)) ? (listener.asBinder()) : (null)));
mRemote.transact(Stub.TRANSACTION_registerListener, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public void unregisterListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((((listener != null)) ? (listener.asBinder()) : (null)));
mRemote.transact(Stub.TRANSACTION_unregisterListener, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
/**
* Control network policies atomically.
*/
@Override
public void setNetworkPolicies(android.net.NetworkPolicy[] policies) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeTypedArray(policies, 0);
mRemote.transact(Stub.TRANSACTION_setNetworkPolicies, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public android.net.NetworkPolicy[] getNetworkPolicies() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
android.net.NetworkPolicy[] _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getNetworkPolicies, _data, _reply, 0);
_reply.readException();
_result = _reply.createTypedArray(android.net.NetworkPolicy.CREATOR);
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
/**
* Snooze limit on policy matching given template.
*/
@Override
public void snoozeLimit(android.net.NetworkTemplate template) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((template != null)) {
_data.writeInt(1);
template.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_snoozeLimit, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
/**
* Control if background data is restricted system-wide.
*/
@Override
public void setRestrictBackground(boolean restrictBackground) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(((restrictBackground) ? (1) : (0)));
mRemote.transact(Stub.TRANSACTION_setRestrictBackground, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public boolean getRestrictBackground() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getRestrictBackground, _data, _reply, 0);
_reply.readException();
_result = (0 != _reply.readInt());
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public android.net.NetworkQuotaInfo getNetworkQuotaInfo(android.net.NetworkState state) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
android.net.NetworkQuotaInfo _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((state != null)) {
_data.writeInt(1);
state.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_getNetworkQuotaInfo, _data, _reply, 0);
_reply.readException();
if ((0 != _reply.readInt())) {
_result = android.net.NetworkQuotaInfo.CREATOR.createFromParcel(_reply);
} else {
_result = null;
}
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public boolean isNetworkMetered(android.net.NetworkState state) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((state != null)) {
_data.writeInt(1);
state.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_isNetworkMetered, _data, _reply, 0);
_reply.readException();
_result = (0 != _reply.readInt());
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_setUidPolicy = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_getUidPolicy = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_getUidsWithPolicy = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
static final int TRANSACTION_isUidForeground = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3);
static final int TRANSACTION_registerListener = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4);
static final int TRANSACTION_unregisterListener = (android.os.IBinder.FIRST_CALL_TRANSACTION + 5);
static final int TRANSACTION_setNetworkPolicies = (android.os.IBinder.FIRST_CALL_TRANSACTION + 6);
static final int TRANSACTION_getNetworkPolicies = (android.os.IBinder.FIRST_CALL_TRANSACTION + 7);
static final int TRANSACTION_snoozeLimit = (android.os.IBinder.FIRST_CALL_TRANSACTION + 8);
static final int TRANSACTION_setRestrictBackground = (android.os.IBinder.FIRST_CALL_TRANSACTION + 9);
static final int TRANSACTION_getRestrictBackground = (android.os.IBinder.FIRST_CALL_TRANSACTION + 10);
static final int TRANSACTION_getNetworkQuotaInfo = (android.os.IBinder.FIRST_CALL_TRANSACTION + 11);
static final int TRANSACTION_isNetworkMetered = (android.os.IBinder.FIRST_CALL_TRANSACTION + 12);
}
/**
* Control UID policies.
*/
public void setUidPolicy(int uid, int policy) throws android.os.RemoteException;
public int getUidPolicy(int uid) throws android.os.RemoteException;
public int[] getUidsWithPolicy(int policy) throws android.os.RemoteException;
public boolean isUidForeground(int uid) throws android.os.RemoteException;
public void registerListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException;
public void unregisterListener(android.net.INetworkPolicyListener listener) throws android.os.RemoteException;
/**
* Control network policies atomically.
*/
public void setNetworkPolicies(android.net.NetworkPolicy[] policies) throws android.os.RemoteException;
public android.net.NetworkPolicy[] getNetworkPolicies() throws android.os.RemoteException;
/**
* Snooze limit on policy matching given template.
*/
public void snoozeLimit(android.net.NetworkTemplate template) throws android.os.RemoteException;
/**
* Control if background data is restricted system-wide.
*/
public void setRestrictBackground(boolean restrictBackground) throws android.os.RemoteException;
public boolean getRestrictBackground() throws android.os.RemoteException;
public android.net.NetworkQuotaInfo getNetworkQuotaInfo(android.net.NetworkState state) throws android.os.RemoteException;
public boolean isNetworkMetered(android.net.NetworkState state) throws android.os.RemoteException;
}
@@ -0,0 +1,152 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.UnknownHostException;
/**
* Identifies an address of a network link
*
* @hide
*/
public class LinkAddress implements Parcelable {
/**
* IPv4 or IPv6 address.
*/
private final InetAddress address;
/**
* Network prefix length
*/
private final int prefixLength;
public LinkAddress(InetAddress address, int prefixLength) {
if (address == null || prefixLength < 0 ||
((address instanceof Inet4Address) && prefixLength > 32) ||
(prefixLength > 128)) {
throw new IllegalArgumentException("Bad LinkAddress haloParams " + address +
prefixLength);
}
this.address = address;
this.prefixLength = prefixLength;
}
public LinkAddress(InterfaceAddress interfaceAddress) {
this.address = interfaceAddress.getAddress();
this.prefixLength = interfaceAddress.getNetworkPrefixLength();
}
@Override
public String toString() {
return (address == null ? "" : (address.getHostAddress() + "/" + prefixLength));
}
/**
* Compares this {@code LinkAddress} instance against the specified address
* in {@code obj}. Two addresses are equal if their InetAddress and prefixLength
* are equal
*
* @param obj the object to be tested for equality.
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LinkAddress)) {
return false;
}
LinkAddress linkAddress = (LinkAddress) obj;
return this.address.equals(linkAddress.address) &&
this.prefixLength == linkAddress.prefixLength;
}
@Override
/*
* generate hashcode based on significant fields
*/
public int hashCode() {
return ((null == address) ? 0 : address.hashCode()) + prefixLength;
}
/**
* Returns the InetAddress for this address.
*/
public InetAddress getAddress() {
return address;
}
/**
* Get network prefix length
*/
public int getNetworkPrefixLength() {
return prefixLength;
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
if (address != null) {
dest.writeByte((byte) 1);
dest.writeByteArray(address.getAddress());
dest.writeInt(prefixLength);
} else {
dest.writeByte((byte) 0);
}
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<LinkAddress> CREATOR =
new Creator<LinkAddress>() {
public LinkAddress createFromParcel(Parcel in) {
InetAddress address = null;
int prefixLength = 0;
if (in.readByte() == 1) {
try {
address = InetAddress.getByAddress(in.createByteArray());
prefixLength = in.readInt();
} catch (UnknownHostException e) {
}
}
return new LinkAddress(address, prefixLength);
}
public LinkAddress[] newArray(int size) {
return new LinkAddress[size];
}
};
}
@@ -0,0 +1,393 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
* A class representing the capabilities of a link
*
* @hide
*/
public class LinkCapabilities implements Parcelable {
private static final String TAG = "LinkCapabilities";
private static final boolean LOCAL_LOGV = false;
/**
* The Map of Keys to Values
*/
private HashMap<Integer, String> mCapabilities;
/**
* The set of keys defined for a links capabilities.
* <p/>
* Keys starting with RW are read + write, i.e. the application
* can request for a certain requirement corresponding to that key.
* Keys starting with RO are read only, i.e. the the application
* can read the value of that key from the socket but cannot request
* a corresponding requirement.
* <p/>
* TODO: Provide a documentation technique for concisely and precisely
* define the syntax for each value string associated with a key.
*/
public static final class Key {
/**
* No constructor
*/
private Key() {
}
/**
* An integer representing the network type.
*
* @see ConnectivityManager
*/
public final static int RO_NETWORK_TYPE = 1;
/**
* Desired minimum forward link (download) bandwidth for the
* in kilobits per second (kbps). Values should be strings such
* "50", "100", "1500", etc.
*/
public final static int RW_DESIRED_FWD_BW = 2;
/**
* Required minimum forward link (download) bandwidth, in
* per second (kbps), below which the socket cannot function.
* Values should be strings such as "50", "100", "1500", etc.
*/
public final static int RW_REQUIRED_FWD_BW = 3;
/**
* Available forward link (download) bandwidth for the socket.
* This value is in kilobits per second (kbps).
* Values will be strings such as "50", "100", "1500", etc.
*/
public final static int RO_AVAILABLE_FWD_BW = 4;
/**
* Desired minimum reverse link (upload) bandwidth for the socket
* in kilobits per second (kbps).
* Values should be strings such as "50", "100", "1500", etc.
* <p/>
* This key is set via the needs map.
*/
public final static int RW_DESIRED_REV_BW = 5;
/**
* Required minimum reverse link (upload) bandwidth, in kilobits
* per second (kbps), below which the socket cannot function.
* If a rate is not specified, the default rate of kbps will be
* Values should be strings such as "50", "100", "1500", etc.
*/
public final static int RW_REQUIRED_REV_BW = 6;
/**
* Available reverse link (upload) bandwidth for the socket.
* This value is in kilobits per second (kbps).
* Values will be strings such as "50", "100", "1500", etc.
*/
public final static int RO_AVAILABLE_REV_BW = 7;
/**
* Maximum latency for the socket, in milliseconds, above which
* socket cannot function.
* Values should be strings such as "50", "300", "500", etc.
*/
public final static int RW_MAX_ALLOWED_LATENCY = 8;
/**
* Interface that the socket is bound to. This can be a virtual
* interface (e.g. VPN or Mobile IP) or a physical interface
* (e.g. wlan0 or rmnet0).
* Values will be strings such as "wlan0", "rmnet0"
*/
public final static int RO_BOUND_INTERFACE = 9;
/**
* Physical interface that the socket is routed on.
* This can be different from BOUND_INTERFACE in cases such as
* VPN or Mobile IP. The physical interface may change over time
* if seamless mobility is supported.
* Values will be strings such as "wlan0", "rmnet0"
*/
public final static int RO_PHYSICAL_INTERFACE = 10;
}
/**
* Role informs the LinkSocket about the data usage patterns of your
* application.
* <p/>
* {@code Role.DEFAULT} is the default role, and is used whenever
* a role isn't set.
*/
public static final class Role {
/**
* No constructor
*/
private Role() {
}
// examples only, discuss which roles should be defined, and then
// code these to match
/**
* Default Role
*/
public static final String DEFAULT = "default";
/**
* Bulk down load
*/
public static final String BULK_DOWNLOAD = "bulk.download";
/**
* Bulk upload
*/
public static final String BULK_UPLOAD = "bulk.upload";
/**
* VoIP Application at 24kbps
*/
public static final String VOIP_24KBPS = "voip.24k";
/**
* VoIP Application at 32kbps
*/
public static final String VOIP_32KBPS = "voip.32k";
/**
* Video Streaming at 480p
*/
public static final String VIDEO_STREAMING_480P = "video.streaming.480p";
/**
* Video Streaming at 720p
*/
public static final String VIDEO_STREAMING_720I = "video.streaming.720i";
/**
* Video Chat Application at 360p
*/
public static final String VIDEO_CHAT_360P = "video.chat.360p";
/**
* Video Chat Application at 480p
*/
public static final String VIDEO_CHAT_480P = "video.chat.480i";
}
/**
* Constructor
*/
public LinkCapabilities() {
mCapabilities = new HashMap<Integer, String>();
}
/**
* Copy constructor.
*
* @param source
*/
public LinkCapabilities(LinkCapabilities source) {
if (source != null) {
mCapabilities = new HashMap<Integer, String>(source.mCapabilities);
} else {
mCapabilities = new HashMap<Integer, String>();
}
}
/**
* Create the {@code LinkCapabilities} with values depending on role type.
*
* @param applicationRole a {@code LinkSocket.Role}
* @return the {@code LinkCapabilities} associated with the applicationRole, empty if none
*/
public static LinkCapabilities createNeedsMap(String applicationRole) {
log("createNeededCapabilities(applicationRole) EX");
return new LinkCapabilities();
}
/**
* Remove all capabilities
*/
public void clear() {
mCapabilities.clear();
}
/**
* Returns whether this map is empty.
*/
public boolean isEmpty() {
return mCapabilities.isEmpty();
}
/**
* Returns the number of elements in this map.
*
* @return the number of elements in this map.
*/
public int size() {
return mCapabilities.size();
}
/**
* Given the key return the capability string
*
* @param key
* @return the capability string
*/
public String get(int key) {
return mCapabilities.get(key);
}
/**
* Store the key/value capability pair
*
* @param key
* @param value
*/
public void put(int key, String value) {
mCapabilities.put(key, value);
}
/**
* Returns whether this map contains the specified key.
*
* @param key to search for.
* @return {@code true} if this map contains the specified key,
* {@code false} otherwise.
*/
public boolean containsKey(int key) {
return mCapabilities.containsKey(key);
}
/**
* Returns whether this map contains the specified value.
*
* @param value to search for.
* @return {@code true} if this map contains the specified value,
* {@code false} otherwise.
*/
public boolean containsValue(String value) {
return mCapabilities.containsValue(value);
}
/**
* Returns a set containing all of the mappings in this map. Each mapping is
* an instance of {@link java.util.Map.Entry}. As the set is backed by this map,
* changes in one will be reflected in the other.
*
* @return a set of the mappings.
*/
public Set<Entry<Integer, String>> entrySet() {
return mCapabilities.entrySet();
}
/**
* @return the set of the keys.
*/
public Set<Integer> keySet() {
return mCapabilities.keySet();
}
/**
* @return the set of values
*/
public Collection<String> values() {
return mCapabilities.values();
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
/**
* Convert to string for debugging
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
boolean firstTime = true;
for (Entry<Integer, String> entry : mCapabilities.entrySet()) {
if (firstTime) {
firstTime = false;
} else {
sb.append(",");
}
sb.append(entry.getKey());
sb.append(":\"");
sb.append(entry.getValue());
sb.append("\"");
return mCapabilities.toString();
}
return sb.toString();
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mCapabilities.size());
for (Entry<Integer, String> entry : mCapabilities.entrySet()) {
dest.writeInt(entry.getKey().intValue());
dest.writeString(entry.getValue());
}
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<LinkCapabilities> CREATOR =
new Creator<LinkCapabilities>() {
public LinkCapabilities createFromParcel(Parcel in) {
LinkCapabilities capabilities = new LinkCapabilities();
int size = in.readInt();
while (size-- != 0) {
int key = in.readInt();
String value = in.readString();
capabilities.mCapabilities.put(key, value);
}
return capabilities;
}
public LinkCapabilities[] newArray(int size) {
return new LinkCapabilities[size];
}
};
/**
* Debug logging
*/
protected static void log(String s) {
if (LOCAL_LOGV) Log.v(TAG, s);
}
}
@@ -0,0 +1,441 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* Describes the properties of a network link.
* <p/>
* A link represents a connection to a network.
* It may have multiple addresses and multiple gateways,
* multiple dns servers but only one http proxy.
* <p/>
* Because it's a single network, the dns's
* are interchangeable and don't need associating with
* particular addresses. The gateways similarly don't
* need associating with particular addresses.
* <p/>
* A dual stack interface works fine in this model:
* each address has it's own prefix length to describe
* the local network. The dns servers all return
* both v4 addresses and v6 addresses regardless of the
* address family of the server itself (rfc4213) and we
* don't care which is used. The gateways will be
* selected based on the destination address and the
* source address has no relavence.
*
* @hide
*/
public class LinkProperties implements Parcelable {
String mIfaceName;
private Collection<LinkAddress> mLinkAddresses = new ArrayList<LinkAddress>();
private Collection<InetAddress> mDnses = new ArrayList<InetAddress>();
private Collection<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
private ProxyProperties mHttpProxy;
public static class CompareResult<T> {
public Collection<T> removed = new ArrayList<T>();
public Collection<T> added = new ArrayList<T>();
@Override
public String toString() {
String retVal = "removed=[";
for (T addr : removed) retVal += addr.toString() + ",";
retVal += "] added=[";
for (T addr : added) retVal += addr.toString() + ",";
retVal += "]";
return retVal;
}
}
public LinkProperties() {
clear();
}
// copy constructor instead of clone
public LinkProperties(LinkProperties source) {
if (source != null) {
mIfaceName = source.getInterfaceName();
for (LinkAddress l : source.getLinkAddresses()) mLinkAddresses.add(l);
for (InetAddress i : source.getDnses()) mDnses.add(i);
for (RouteInfo r : source.getRoutes()) mRoutes.add(r);
mHttpProxy = (source.getHttpProxy() == null) ?
null : new ProxyProperties(source.getHttpProxy());
}
}
public void setInterfaceName(String iface) {
mIfaceName = iface;
}
public String getInterfaceName() {
return mIfaceName;
}
public Collection<InetAddress> getAddresses() {
Collection<InetAddress> addresses = new ArrayList<InetAddress>();
for (LinkAddress linkAddress : mLinkAddresses) {
addresses.add(linkAddress.getAddress());
}
return Collections.unmodifiableCollection(addresses);
}
public void addLinkAddress(LinkAddress address) {
if (address != null) mLinkAddresses.add(address);
}
public Collection<LinkAddress> getLinkAddresses() {
return Collections.unmodifiableCollection(mLinkAddresses);
}
public void addDns(InetAddress dns) {
if (dns != null) mDnses.add(dns);
}
public Collection<InetAddress> getDnses() {
return Collections.unmodifiableCollection(mDnses);
}
public void addRoute(RouteInfo route) {
if (route != null) mRoutes.add(route);
}
public Collection<RouteInfo> getRoutes() {
return Collections.unmodifiableCollection(mRoutes);
}
public void setHttpProxy(ProxyProperties proxy) {
mHttpProxy = proxy;
}
public ProxyProperties getHttpProxy() {
return mHttpProxy;
}
public void clear() {
mIfaceName = null;
mLinkAddresses.clear();
mDnses.clear();
mRoutes.clear();
mHttpProxy = null;
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
@Override
public String toString() {
String ifaceName = (mIfaceName == null ? "" : "InterfaceName: " + mIfaceName + " ");
String linkAddresses = "LinkAddresses: [";
for (LinkAddress addr : mLinkAddresses) linkAddresses += addr.toString() + ",";
linkAddresses += "] ";
String dns = "DnsAddresses: [";
for (InetAddress addr : mDnses) dns += addr.getHostAddress() + ",";
dns += "] ";
String routes = "Routes: [";
for (RouteInfo route : mRoutes) routes += route.toString() + ",";
routes += "] ";
String proxy = (mHttpProxy == null ? "" : "HttpProxy: " + mHttpProxy.toString() + " ");
return ifaceName + linkAddresses + routes + dns + proxy;
}
/**
* Compares this {@code LinkProperties} interface name against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalInterfaceName(LinkProperties target) {
return TextUtils.equals(getInterfaceName(), target.getInterfaceName());
}
/**
* Compares this {@code LinkProperties} interface name against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalAddresses(LinkProperties target) {
Collection<InetAddress> targetAddresses = target.getAddresses();
Collection<InetAddress> sourceAddresses = getAddresses();
return (sourceAddresses.size() == targetAddresses.size()) ?
sourceAddresses.containsAll(targetAddresses) : false;
}
/**
* Compares this {@code LinkProperties} DNS addresses against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalDnses(LinkProperties target) {
Collection<InetAddress> targetDnses = target.getDnses();
return (mDnses.size() == targetDnses.size()) ?
mDnses.containsAll(targetDnses) : false;
}
/**
* Compares this {@code LinkProperties} Routes against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalRoutes(LinkProperties target) {
Collection<RouteInfo> targetRoutes = target.getRoutes();
return (mRoutes.size() == targetRoutes.size()) ?
mRoutes.containsAll(targetRoutes) : false;
}
/**
* Compares this {@code LinkProperties} HttpProxy against the target
*
* @param target LinkProperties to compare.
* @return {@code true} if both are identical, {@code false} otherwise.
*/
public boolean isIdenticalHttpProxy(LinkProperties target) {
return getHttpProxy() == null ? target.getHttpProxy() == null :
getHttpProxy().equals(target.getHttpProxy());
}
@Override
/**
* Compares this {@code LinkProperties} instance against the target
* LinkProperties in {@code obj}. Two LinkPropertieses are equal if
* all their fields are equal in values.
*
* For collection fields, such as mDnses, containsAll() is used to check
* if two collections contains the same elements, independent of order.
* There are two thoughts regarding containsAll()
* 1. Duplicated elements. eg, (A, B, B) and (A, A, B) are equal.
* 2. Worst case performance is O(n^2).
*
* @param obj the object to be tested for equality.
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof LinkProperties)) return false;
LinkProperties target = (LinkProperties) obj;
return isIdenticalInterfaceName(target) &&
isIdenticalAddresses(target) &&
isIdenticalDnses(target) &&
isIdenticalRoutes(target) &&
isIdenticalHttpProxy(target);
}
/**
* Return two lists, a list of addresses that would be removed from
* mLinkAddresses and a list of addresses that would be added to
* mLinkAddress which would then result in target and mLinkAddresses
* being the same list.
*
* @param target is a LinkProperties with the new list of addresses
* @return the removed and added lists.
*/
public CompareResult<LinkAddress> compareAddresses(LinkProperties target) {
/*
* Duplicate the LinkAddresses into removed, we will be removing
* address which are common between mLinkAddresses and target
* leaving the addresses that are different. And address which
* are in target but not in mLinkAddresses are placed in the
* addedAddresses.
*/
CompareResult<LinkAddress> result = new CompareResult<LinkAddress>();
result.removed = new ArrayList<LinkAddress>(mLinkAddresses);
result.added.clear();
if (target != null) {
for (LinkAddress newAddress : target.getLinkAddresses()) {
if (!result.removed.remove(newAddress)) {
result.added.add(newAddress);
}
}
}
return result;
}
/**
* Return two lists, a list of dns addresses that would be removed from
* mDnses and a list of addresses that would be added to
* mDnses which would then result in target and mDnses
* being the same list.
*
* @param target is a LinkProperties with the new list of dns addresses
* @return the removed and added lists.
*/
public CompareResult<InetAddress> compareDnses(LinkProperties target) {
/*
* Duplicate the InetAddresses into removed, we will be removing
* dns address which are common between mDnses and target
* leaving the addresses that are different. And dns address which
* are in target but not in mDnses are placed in the
* addedAddresses.
*/
CompareResult<InetAddress> result = new CompareResult<InetAddress>();
result.removed = new ArrayList<InetAddress>(mDnses);
result.added.clear();
if (target != null) {
for (InetAddress newAddress : target.getDnses()) {
if (!result.removed.remove(newAddress)) {
result.added.add(newAddress);
}
}
}
return result;
}
/**
* Return two lists, a list of routes that would be removed from
* mRoutes and a list of routes that would be added to
* mRoutes which would then result in target and mRoutes
* being the same list.
*
* @param target is a LinkProperties with the new list of routes
* @return the removed and added lists.
*/
public CompareResult<RouteInfo> compareRoutes(LinkProperties target) {
/*
* Duplicate the RouteInfos into removed, we will be removing
* routes which are common between mDnses and target
* leaving the routes that are different. And route address which
* are in target but not in mRoutes are placed in added.
*/
CompareResult<RouteInfo> result = new CompareResult<RouteInfo>();
result.removed = new ArrayList<RouteInfo>(mRoutes);
result.added.clear();
if (target != null) {
for (RouteInfo r : target.getRoutes()) {
if (!result.removed.remove(r)) {
result.added.add(r);
}
}
}
return result;
}
@Override
/**
* generate hashcode based on significant fields
* Equal objects must produce the same hash code, while unequal objects
* may have the same hash codes.
*/
public int hashCode() {
return ((null == mIfaceName) ? 0 : mIfaceName.hashCode()
+ mLinkAddresses.size() * 31
+ mDnses.size() * 37
+ mRoutes.size() * 41
+ ((null == mHttpProxy) ? 0 : mHttpProxy.hashCode()));
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getInterfaceName());
dest.writeInt(mLinkAddresses.size());
for (LinkAddress linkAddress : mLinkAddresses) {
dest.writeParcelable(linkAddress, flags);
}
dest.writeInt(mDnses.size());
for (InetAddress d : mDnses) {
dest.writeByteArray(d.getAddress());
}
dest.writeInt(mRoutes.size());
for (RouteInfo route : mRoutes) {
dest.writeParcelable(route, flags);
}
if (mHttpProxy != null) {
dest.writeByte((byte) 1);
dest.writeParcelable(mHttpProxy, flags);
} else {
dest.writeByte((byte) 0);
}
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<LinkProperties> CREATOR =
new Creator<LinkProperties>() {
public LinkProperties createFromParcel(Parcel in) {
LinkProperties netProp = new LinkProperties();
String iface = in.readString();
if (iface != null) {
try {
netProp.setInterfaceName(iface);
} catch (Exception e) {
return null;
}
}
int addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
netProp.addLinkAddress((LinkAddress) in.readParcelable(null));
}
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
try {
netProp.addDns(InetAddress.getByAddress(in.createByteArray()));
} catch (UnknownHostException e) {
}
}
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
netProp.addRoute((RouteInfo) in.readParcelable(null));
}
if (in.readByte() == 1) {
netProp.setHttpProxy((ProxyProperties) in.readParcelable(null));
}
return netProp;
}
public LinkProperties[] newArray(int size) {
return new LinkProperties[size];
}
};
}
@@ -0,0 +1,229 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import com.android.internal.util.Objects;
import static android.net.ConnectivityManager.TYPE_WIFI;
/**
* Network definition that includes strong identity. Analogous to combining
* {@link NetworkInfo} and an IMSI.
*
* @hide
*/
public class NetworkIdentity {
/**
* When enabled, combine all {@link #mSubType} together under
* {@link #SUBTYPE_COMBINED}.
*/
public static final boolean COMBINE_SUBTYPE_ENABLED = true;
public static final int SUBTYPE_COMBINED = -1;
final int mType;
final int mSubType;
final String mSubscriberId;
final String mNetworkId;
final boolean mRoaming;
public NetworkIdentity(
int type, int subType, String subscriberId, String networkId, boolean roaming) {
mType = type;
mSubType = COMBINE_SUBTYPE_ENABLED ? SUBTYPE_COMBINED : subType;
mSubscriberId = subscriberId;
mNetworkId = networkId;
mRoaming = roaming;
}
/**
* {@hide}
*/
public static String getNetworkTypeName(int type) {
switch (type) {
case 0:
return "MOBILE";
case TYPE_WIFI:
return "WIFI";
case 2:
return "MOBILE_MMS";
case 3:
return "MOBILE_SUPL";
case 4:
return "MOBILE_DUN";
case 5:
return "MOBILE_HIPRI";
case 6:
return "WIMAX";
case 7:
return "BLUETOOTH";
case 8:
return "DUMMY";
case 9:
return "ETHERNET";
case 10:
return "MOBILE_FOTA";
case 11:
return "MOBILE_IMS";
case 12:
return "MOBILE_CBS";
case 13:
return "WIFI_P2P";
default:
return Integer.toString(type);
}
}
/**
* {@hide}
*/
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case 0:
case 2:
case 3:
case 4:
case 5:
case 10:
case 11:
case 12:
return true;
default:
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(mType, mSubType, mSubscriberId, mNetworkId, mRoaming);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NetworkIdentity) {
final NetworkIdentity ident = (NetworkIdentity) obj;
return mType == ident.mType && mSubType == ident.mSubType && mRoaming == ident.mRoaming
&& Objects.equal(mSubscriberId, ident.mSubscriberId)
&& Objects.equal(mNetworkId, ident.mNetworkId);
}
return false;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("[");
builder.append("type=").append(getNetworkTypeName(mType));
builder.append(", subType=");
if (COMBINE_SUBTYPE_ENABLED) {
builder.append("COMBINED");
} else if (isNetworkTypeMobile(mType)) {
builder.append(getNetworkTypeName(mSubType));
} else {
builder.append(mSubType);
}
if (mSubscriberId != null) {
builder.append(", subscriberId=").append(scrubSubscriberId(mSubscriberId));
}
if (mNetworkId != null) {
builder.append(", networkId=").append(mNetworkId);
}
if (mRoaming) {
builder.append(", ROAMING");
}
return builder.append("]").toString();
}
public int getType() {
return mType;
}
public int getSubType() {
return mSubType;
}
public String getSubscriberId() {
return mSubscriberId;
}
public String getNetworkId() {
return mNetworkId;
}
public boolean getRoaming() {
return mRoaming;
}
/**
* Scrub given IMSI on production builds.
*/
public static String scrubSubscriberId(String subscriberId) {
if ("eng".equals(Build.TYPE)) {
return subscriberId;
} else if (subscriberId != null) {
// TODO: parse this as MCC+MNC instead of hard-coding
return subscriberId.substring(0, Math.min(6, subscriberId.length())) + "...";
} else {
return "null";
}
}
/**
* Build a {@link android.net.NetworkIdentity} from the given {@link NetworkState},
* assuming that any mobile networks are using the current IMSI.
*/
public static NetworkIdentity buildNetworkIdentity(Context context, NetworkState state) {
final int type = state.networkInfo.getType();
final int subType = state.networkInfo.getSubtype();
// TODO: consider moving subscriberId over to LinkCapabilities, so it
// comes from an authoritative source.
String subscriberId = null;
String networkId = null;
boolean roaming = false;
if (isNetworkTypeMobile(type)) {
final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
roaming = telephony.isNetworkRoaming();
if (state.subscriberId != null) {
subscriberId = state.subscriberId;
} else {
subscriberId = telephony.getSubscriberId();
}
} else if (type == TYPE_WIFI) {
if (state.networkId != null) {
networkId = state.networkId;
} else {
final WifiManager wifi = (WifiManager) context.getSystemService(
Context.WIFI_SERVICE);
final WifiInfo info = wifi.getConnectionInfo();
networkId = info != null ? info.getSSID() : null;
}
}
return new NetworkIdentity(type, subType, subscriberId, networkId, roaming);
}
}
@@ -0,0 +1,195 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.util.Objects;
import static com.android.internal.util.Preconditions.checkNotNull;
/**
* Policy for networks matching a {@link NetworkTemplate}, including usage cycle
* and limits to be enforced.
*
* @hide
*/
public class NetworkPolicy implements Parcelable, Comparable<NetworkPolicy> {
public static final int CYCLE_NONE = -1;
public static final long WARNING_DISABLED = -1;
public static final long LIMIT_DISABLED = -1;
public static final long SNOOZE_NEVER = -1;
public final NetworkTemplate template;
public int cycleDay;
public String cycleTimezone;
public long warningBytes;
public long limitBytes;
public long lastWarningSnooze;
public long lastLimitSnooze;
public boolean metered;
public boolean inferred;
private static final long DEFAULT_MTU = 1500;
@Deprecated
public NetworkPolicy(NetworkTemplate template, int cycleDay, String cycleTimezone,
long warningBytes, long limitBytes, boolean metered) {
this(template, cycleDay, cycleTimezone, warningBytes, limitBytes, SNOOZE_NEVER,
SNOOZE_NEVER, metered, false);
}
public NetworkPolicy(NetworkTemplate template, int cycleDay, String cycleTimezone,
long warningBytes, long limitBytes, long lastWarningSnooze, long lastLimitSnooze,
boolean metered, boolean inferred) {
this.template = checkNotNull(template, "missing NetworkTemplate");
this.cycleDay = cycleDay;
this.cycleTimezone = checkNotNull(cycleTimezone, "missing cycleTimezone");
this.warningBytes = warningBytes;
this.limitBytes = limitBytes;
this.lastWarningSnooze = lastWarningSnooze;
this.lastLimitSnooze = lastLimitSnooze;
this.metered = metered;
this.inferred = inferred;
}
public NetworkPolicy(Parcel in) {
template = in.readParcelable(null);
cycleDay = in.readInt();
cycleTimezone = in.readString();
warningBytes = in.readLong();
limitBytes = in.readLong();
lastWarningSnooze = in.readLong();
lastLimitSnooze = in.readLong();
metered = in.readInt() != 0;
inferred = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(template, flags);
dest.writeInt(cycleDay);
dest.writeString(cycleTimezone);
dest.writeLong(warningBytes);
dest.writeLong(limitBytes);
dest.writeLong(lastWarningSnooze);
dest.writeLong(lastLimitSnooze);
dest.writeInt(metered ? 1 : 0);
dest.writeInt(inferred ? 1 : 0);
}
@Override
public int describeContents() {
return 0;
}
/**
* Test if given measurement is over {@link #warningBytes}.
*/
public boolean isOverWarning(long totalBytes) {
return warningBytes != WARNING_DISABLED && totalBytes >= warningBytes;
}
/**
* Test if given measurement is near enough to {@link #limitBytes} to be
* considered over-limit.
*/
public boolean isOverLimit(long totalBytes) {
// over-estimate, since kernel will trigger limit once first packet
// trips over limit.
totalBytes += 2 * DEFAULT_MTU;
return limitBytes != LIMIT_DISABLED && totalBytes >= limitBytes;
}
/**
* Clear any existing snooze values, setting to {@link #SNOOZE_NEVER}.
*/
public void clearSnooze() {
lastWarningSnooze = SNOOZE_NEVER;
lastLimitSnooze = SNOOZE_NEVER;
}
/**
* Test if this policy has a cycle defined, after which usage should reset.
*/
public boolean hasCycle() {
return cycleDay != CYCLE_NONE;
}
@Override
public int compareTo(NetworkPolicy another) {
if (another == null || another.limitBytes == LIMIT_DISABLED) {
// other value is missing or disabled; we win
return -1;
}
if (limitBytes == LIMIT_DISABLED || another.limitBytes < limitBytes) {
// we're disabled or other limit is smaller; they win
return 1;
}
return 0;
}
@Override
public int hashCode() {
return Objects.hashCode(template, cycleDay, cycleTimezone, warningBytes, limitBytes,
lastWarningSnooze, lastLimitSnooze, metered, inferred);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NetworkPolicy) {
final NetworkPolicy other = (NetworkPolicy) obj;
return cycleDay == other.cycleDay && warningBytes == other.warningBytes
&& limitBytes == other.limitBytes
&& lastWarningSnooze == other.lastWarningSnooze
&& lastLimitSnooze == other.lastLimitSnooze && metered == other.metered
&& inferred == other.inferred
&& Objects.equal(cycleTimezone, other.cycleTimezone)
&& Objects.equal(template, other.template);
}
return false;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("NetworkPolicy");
builder.append("[").append(template).append("]:");
builder.append(" cycleDay=").append(cycleDay);
builder.append(", cycleTimezone=").append(cycleTimezone);
builder.append(", warningBytes=").append(warningBytes);
builder.append(", limitBytes=").append(limitBytes);
builder.append(", lastWarningSnooze=").append(lastWarningSnooze);
builder.append(", lastLimitSnooze=").append(lastLimitSnooze);
builder.append(", metered=").append(metered);
builder.append(", inferred=").append(inferred);
return builder.toString();
}
public static final Creator<NetworkPolicy> CREATOR = new Creator<NetworkPolicy>() {
@Override
public NetworkPolicy createFromParcel(Parcel in) {
return new NetworkPolicy(in);
}
@Override
public NetworkPolicy[] newArray(int size) {
return new NetworkPolicy[size];
}
};
}
@@ -0,0 +1,299 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.RemoteException;
import android.text.format.Time;
import com.google.android.collect.Sets;
import java.io.PrintWriter;
import java.util.HashSet;
import static android.content.pm.PackageManager.GET_SIGNATURES;
import static android.net.NetworkPolicy.CYCLE_NONE;
import static android.text.format.Time.MONTH_DAY;
/**
* Manager for creating and modifying network policy rules.
* <p/>
* {@hide}
*/
public class NetworkPolicyManager {
/**
* No specific network policy, use system default.
*/
public static final int POLICY_NONE = 0x0;
/**
* Reject network usage on metered networks when application in background.
*/
public static final int POLICY_REJECT_METERED_BACKGROUND = 0x1;
/**
* All network traffic should be allowed.
*/
public static final int RULE_ALLOW_ALL = 0x0;
/**
* Reject traffic on metered networks.
*/
public static final int RULE_REJECT_METERED = 0x1;
private static final boolean ALLOW_PLATFORM_APP_POLICY = true;
/**
* {@link Intent} extra that indicates which {@link NetworkTemplate} rule it
* applies to.
*/
public static final String EXTRA_NETWORK_TEMPLATE = "android.net.NETWORK_TEMPLATE";
private INetworkPolicyManager mService;
public NetworkPolicyManager(INetworkPolicyManager service) {
if (service == null) {
throw new IllegalArgumentException("missing INetworkPolicyManager");
}
mService = service;
}
public static NetworkPolicyManager from(Context context) {
return (NetworkPolicyManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* Set policy flags for specific UID.
*
* @param policy {@link #POLICY_NONE} or combination of flags like
* {@link #POLICY_REJECT_METERED_BACKGROUND}.
*/
public void setUidPolicy(int uid, int policy) {
try {
mService.setUidPolicy(uid, policy);
} catch (RemoteException e) {
}
}
public int getUidPolicy(int uid) {
try {
return mService.getUidPolicy(uid);
} catch (RemoteException e) {
return POLICY_NONE;
}
}
public int[] getUidsWithPolicy(int policy) {
try {
return mService.getUidsWithPolicy(policy);
} catch (RemoteException e) {
return new int[0];
}
}
public void registerListener(INetworkPolicyListener listener) {
try {
mService.registerListener(listener);
} catch (RemoteException e) {
}
}
public void unregisterListener(INetworkPolicyListener listener) {
try {
mService.unregisterListener(listener);
} catch (RemoteException e) {
}
}
public void setNetworkPolicies(NetworkPolicy[] policies) {
try {
mService.setNetworkPolicies(policies);
} catch (RemoteException e) {
}
}
public NetworkPolicy[] getNetworkPolicies() {
try {
return mService.getNetworkPolicies();
} catch (RemoteException e) {
return null;
}
}
public void setRestrictBackground(boolean restrictBackground) {
try {
mService.setRestrictBackground(restrictBackground);
} catch (RemoteException e) {
}
}
public boolean getRestrictBackground() {
try {
return mService.getRestrictBackground();
} catch (RemoteException e) {
return false;
}
}
/**
* Compute the last cycle boundary for the given {@link NetworkPolicy}. For
* example, if cycle day is 20th, and today is June 15th, it will return May
* 20th. When cycle day doesn't exist in current month, it snaps to the 1st
* of following month.
*
* @hide
*/
public static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
if (policy.cycleDay == CYCLE_NONE) {
throw new IllegalArgumentException("Unable to compute boundary without cycleDay");
}
final Time now = new Time(policy.cycleTimezone);
now.set(currentTime);
// first, find cycle boundary for current month
final Time cycle = new Time(now);
cycle.hour = cycle.minute = cycle.second = 0;
snapToCycleDay(cycle, policy.cycleDay);
if (Time.compare(cycle, now) >= 0) {
// cycle boundary is beyond now, use last cycle boundary; start by
// pushing ourselves squarely into last month.
final Time lastMonth = new Time(now);
lastMonth.hour = lastMonth.minute = lastMonth.second = 0;
lastMonth.monthDay = 1;
lastMonth.month -= 1;
lastMonth.normalize(true);
cycle.set(lastMonth);
snapToCycleDay(cycle, policy.cycleDay);
}
return cycle.toMillis(true);
}
/**
* {@hide}
*/
public static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
if (policy.cycleDay == CYCLE_NONE) {
throw new IllegalArgumentException("Unable to compute boundary without cycleDay");
}
final Time now = new Time(policy.cycleTimezone);
now.set(currentTime);
// first, find cycle boundary for current month
final Time cycle = new Time(now);
cycle.hour = cycle.minute = cycle.second = 0;
snapToCycleDay(cycle, policy.cycleDay);
if (Time.compare(cycle, now) <= 0) {
// cycle boundary is before now, use next cycle boundary; start by
// pushing ourselves squarely into next month.
final Time nextMonth = new Time(now);
nextMonth.hour = nextMonth.minute = nextMonth.second = 0;
nextMonth.monthDay = 1;
nextMonth.month += 1;
nextMonth.normalize(true);
cycle.set(nextMonth);
snapToCycleDay(cycle, policy.cycleDay);
}
return cycle.toMillis(true);
}
/**
* Snap to the cycle day for the current month given; when cycle day doesn't
* exist, it snaps to last second of current month.
*
* @hide
*/
public static void snapToCycleDay(Time time, int cycleDay) {
if (cycleDay > time.getActualMaximum(MONTH_DAY)) {
// cycle day isn't valid this month; snap to last second of month
time.month += 1;
time.monthDay = 1;
time.second = -1;
} else {
time.monthDay = cycleDay;
}
time.normalize(true);
}
/**
* Check if given UID can have a {@link #setUidPolicy(int, int)} defined,
* usually to protect critical system services.
*/
@Deprecated
public static boolean isUidValidForPolicy(Context context, int uid) {
if (!ALLOW_PLATFORM_APP_POLICY) {
final PackageManager pm = context.getPackageManager();
final HashSet<Signature> systemSignature;
try {
systemSignature = Sets.newHashSet(
pm.getPackageInfo("android", GET_SIGNATURES).signatures);
} catch (NameNotFoundException e) {
throw new RuntimeException("problem finding system signature", e);
}
try {
// reject apps signed with platform cert
for (String packageName : pm.getPackagesForUid(uid)) {
final HashSet<Signature> packageSignature = Sets.newHashSet(
pm.getPackageInfo(packageName, GET_SIGNATURES).signatures);
if (packageSignature.containsAll(systemSignature)) {
return false;
}
}
} catch (NameNotFoundException e) {
}
}
// nothing found above; we can apply policy to UID
return true;
}
/**
* {@hide}
*/
public static void dumpPolicy(PrintWriter fout, int policy) {
fout.write("[");
if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
fout.write("REJECT_METERED_BACKGROUND");
}
fout.write("]");
}
/**
* {@hide}
*/
public static void dumpRules(PrintWriter fout, int rules) {
fout.write("[");
if ((rules & RULE_REJECT_METERED) != 0) {
fout.write("REJECT_METERED");
}
fout.write("]");
}
}
@@ -0,0 +1,87 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Information about quota status on a specific network.
*
* @hide
*/
public class NetworkQuotaInfo implements Parcelable {
private final long mEstimatedBytes;
private final long mSoftLimitBytes;
private final long mHardLimitBytes;
public static final long NO_LIMIT = -1;
/**
* {@hide}
*/
public NetworkQuotaInfo(long estimatedBytes, long softLimitBytes, long hardLimitBytes) {
mEstimatedBytes = estimatedBytes;
mSoftLimitBytes = softLimitBytes;
mHardLimitBytes = hardLimitBytes;
}
/**
* {@hide}
*/
public NetworkQuotaInfo(Parcel in) {
mEstimatedBytes = in.readLong();
mSoftLimitBytes = in.readLong();
mHardLimitBytes = in.readLong();
}
public long getEstimatedBytes() {
return mEstimatedBytes;
}
public long getSoftLimitBytes() {
return mSoftLimitBytes;
}
public long getHardLimitBytes() {
return mHardLimitBytes;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeLong(mEstimatedBytes);
out.writeLong(mSoftLimitBytes);
out.writeLong(mHardLimitBytes);
}
public static final Creator<NetworkQuotaInfo> CREATOR = new Creator<NetworkQuotaInfo>() {
@Override
public NetworkQuotaInfo createFromParcel(Parcel in) {
return new NetworkQuotaInfo(in);
}
@Override
public NetworkQuotaInfo[] newArray(int size) {
return new NetworkQuotaInfo[size];
}
};
}
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Snapshot of network state.
*
* @hide
*/
public class NetworkState implements Parcelable {
public final NetworkInfo networkInfo;
public final LinkProperties linkProperties;
public final LinkCapabilities linkCapabilities;
/**
* Currently only used by testing.
*/
public final String subscriberId;
public final String networkId;
public NetworkState(NetworkInfo networkInfo, LinkProperties linkProperties,
LinkCapabilities linkCapabilities) {
this(networkInfo, linkProperties, linkCapabilities, null, null);
}
public NetworkState(NetworkInfo networkInfo, LinkProperties linkProperties,
LinkCapabilities linkCapabilities, String subscriberId, String networkId) {
this.networkInfo = networkInfo;
this.linkProperties = linkProperties;
this.linkCapabilities = linkCapabilities;
this.subscriberId = subscriberId;
this.networkId = networkId;
}
public NetworkState(Parcel in) {
networkInfo = in.readParcelable(null);
linkProperties = in.readParcelable(null);
linkCapabilities = in.readParcelable(null);
subscriberId = in.readString();
networkId = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeParcelable(networkInfo, flags);
out.writeParcelable(linkProperties, flags);
out.writeParcelable(linkCapabilities, flags);
out.writeString(subscriberId);
out.writeString(networkId);
}
public static final Creator<NetworkState> CREATOR = new Creator<NetworkState>() {
@Override
public NetworkState createFromParcel(Parcel in) {
return new NetworkState(in);
}
@Override
public NetworkState[] newArray(int size) {
return new NetworkState[size];
}
};
}
@@ -0,0 +1,457 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Objects;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;
import static android.net.NetworkIdentity.COMBINE_SUBTYPE_ENABLED;
import static android.net.NetworkIdentity.scrubSubscriberId;
import static com.android.internal.util.ArrayUtils.contains;
/**
* Template definition used to generically match {@link NetworkIdentity},
* usually when collecting statistics.
*
* @hide
*/
public class NetworkTemplate implements Parcelable {
public static final int MATCH_MOBILE_ALL = 1;
public static final int MATCH_MOBILE_3G_LOWER = 2;
public static final int MATCH_MOBILE_4G = 3;
public static final int MATCH_WIFI = 4;
public static final int MATCH_ETHERNET = 5;
public static final int MATCH_MOBILE_WILDCARD = 6;
public static final int MATCH_WIFI_WILDCARD = 7;
/**
* Network type is unknown
*/
public static final int NETWORK_TYPE_UNKNOWN = 0;
/**
* Current network is GPRS
*/
public static final int NETWORK_TYPE_GPRS = 1;
/**
* Current network is EDGE
*/
public static final int NETWORK_TYPE_EDGE = 2;
/**
* Current network is UMTS
*/
public static final int NETWORK_TYPE_UMTS = 3;
/**
* Current network is CDMA: Either IS95A or IS95B
*/
public static final int NETWORK_TYPE_CDMA = 4;
/**
* Current network is EVDO revision 0
*/
public static final int NETWORK_TYPE_EVDO_0 = 5;
/**
* Current network is EVDO revision A
*/
public static final int NETWORK_TYPE_EVDO_A = 6;
/**
* Current network is 1xRTT
*/
public static final int NETWORK_TYPE_1xRTT = 7;
/**
* Current network is HSDPA
*/
public static final int NETWORK_TYPE_HSDPA = 8;
/**
* Current network is HSUPA
*/
public static final int NETWORK_TYPE_HSUPA = 9;
/**
* Current network is HSPA
*/
public static final int NETWORK_TYPE_HSPA = 10;
/**
* Current network is iDen
*/
public static final int NETWORK_TYPE_IDEN = 11;
/**
* Current network is EVDO revision B
*/
public static final int NETWORK_TYPE_EVDO_B = 12;
/**
* Current network is LTE
*/
public static final int NETWORK_TYPE_LTE = 13;
/**
* Current network is eHRPD
*/
public static final int NETWORK_TYPE_EHRPD = 14;
/**
* Current network is HSPA+
*/
public static final int NETWORK_TYPE_HSPAP = 15;
/**
* Unknown network class. {@hide}
*/
public static final int NETWORK_CLASS_UNKNOWN = 0;
/**
* Class of broadly defined "2G" networks. {@hide}
*/
public static final int NETWORK_CLASS_2_G = 1;
/**
* Class of broadly defined "3G" networks. {@hide}
*/
public static final int NETWORK_CLASS_3_G = 2;
/**
* Class of broadly defined "4G" networks. {@hide}
*/
public static final int NETWORK_CLASS_4_G = 3;
/**
* Return general class of network type, such as "3G" or "4G". In cases
* where classification is contentious, this method is conservative.
*
* @hide
*/
public static int getNetworkClass(int networkType) {
switch (networkType) {
case NETWORK_TYPE_GPRS:
case NETWORK_TYPE_EDGE:
case NETWORK_TYPE_CDMA:
case NETWORK_TYPE_1xRTT:
case NETWORK_TYPE_IDEN:
return NETWORK_CLASS_2_G;
case NETWORK_TYPE_UMTS:
case NETWORK_TYPE_EVDO_0:
case NETWORK_TYPE_EVDO_A:
case NETWORK_TYPE_HSDPA:
case NETWORK_TYPE_HSUPA:
case NETWORK_TYPE_HSPA:
case NETWORK_TYPE_EVDO_B:
case NETWORK_TYPE_EHRPD:
case NETWORK_TYPE_HSPAP:
return NETWORK_CLASS_3_G;
case NETWORK_TYPE_LTE:
return NETWORK_CLASS_4_G;
default:
return NETWORK_CLASS_UNKNOWN;
}
}
/**
* Set of {@link NetworkInfo#getType()} that reflect data usage.
*/
private static final int[] DATA_USAGE_NETWORK_TYPES = {0};
private static boolean sForceAllNetworkTypes = false;
@VisibleForTesting
public static void forceAllNetworkTypes() {
sForceAllNetworkTypes = true;
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks with
* the given IMSI.
*/
public static NetworkTemplate buildTemplateMobileAll(String subscriberId) {
return new NetworkTemplate(MATCH_MOBILE_ALL, subscriberId, null);
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks with
* the given IMSI that roughly meet a "3G" definition, or lower.
*/
@Deprecated
public static NetworkTemplate buildTemplateMobile3gLower(String subscriberId) {
return new NetworkTemplate(MATCH_MOBILE_3G_LOWER, subscriberId, null);
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks with
* the given IMSI that roughly meet a "4G" definition.
*/
@Deprecated
public static NetworkTemplate buildTemplateMobile4g(String subscriberId) {
return new NetworkTemplate(MATCH_MOBILE_4G, subscriberId, null);
}
/**
* Template to match {@link ConnectivityManager#TYPE_MOBILE} networks,
* regardless of IMSI.
*/
public static NetworkTemplate buildTemplateMobileWildcard() {
return new NetworkTemplate(MATCH_MOBILE_WILDCARD, null, null);
}
/**
* Template to match all {@link ConnectivityManager#TYPE_WIFI} networks,
* regardless of SSID.
*/
public static NetworkTemplate buildTemplateWifiWildcard() {
return new NetworkTemplate(MATCH_WIFI_WILDCARD, null, null);
}
@Deprecated
public static NetworkTemplate buildTemplateWifi() {
return buildTemplateWifiWildcard();
}
/**
* Template to match {@link ConnectivityManager#TYPE_WIFI} networks with the
* given SSID.
*/
public static NetworkTemplate buildTemplateWifi(String networkId) {
return new NetworkTemplate(MATCH_WIFI, null, networkId);
}
/**
* Template to combine all {@link ConnectivityManager#TYPE_ETHERNET} style
* networks together.
*/
public static NetworkTemplate buildTemplateEthernet() {
return new NetworkTemplate(MATCH_ETHERNET, null, null);
}
private final int mMatchRule;
private final String mSubscriberId;
private final String mNetworkId;
public NetworkTemplate(int matchRule, String subscriberId, String networkId) {
mMatchRule = matchRule;
mSubscriberId = subscriberId;
mNetworkId = networkId;
}
private NetworkTemplate(Parcel in) {
mMatchRule = in.readInt();
mSubscriberId = in.readString();
mNetworkId = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mMatchRule);
dest.writeString(mSubscriberId);
dest.writeString(mNetworkId);
}
@Override
public int describeContents() {
return 0;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("NetworkTemplate: ");
builder.append("matchRule=").append(getMatchRuleName(mMatchRule));
if (mSubscriberId != null) {
builder.append(", subscriberId=").append(scrubSubscriberId(mSubscriberId));
}
if (mNetworkId != null) {
builder.append(", networkId=").append(mNetworkId);
}
return builder.toString();
}
@Override
public int hashCode() {
return Objects.hashCode(mMatchRule, mSubscriberId, mNetworkId);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NetworkTemplate) {
final NetworkTemplate other = (NetworkTemplate) obj;
return mMatchRule == other.mMatchRule
&& Objects.equal(mSubscriberId, other.mSubscriberId)
&& Objects.equal(mNetworkId, other.mNetworkId);
}
return false;
}
public int getMatchRule() {
return mMatchRule;
}
public String getSubscriberId() {
return mSubscriberId;
}
public String getNetworkId() {
return mNetworkId;
}
/**
* Test if given {@link NetworkIdentity} matches this template.
*/
public boolean matches(NetworkIdentity ident) {
switch (mMatchRule) {
case MATCH_MOBILE_ALL:
return matchesMobile(ident);
case MATCH_MOBILE_3G_LOWER:
return matchesMobile3gLower(ident);
case MATCH_MOBILE_4G:
return matchesMobile4g(ident);
case MATCH_WIFI:
return matchesWifi(ident);
case MATCH_ETHERNET:
return matchesEthernet(ident);
case MATCH_MOBILE_WILDCARD:
return matchesMobileWildcard(ident);
case MATCH_WIFI_WILDCARD:
return matchesWifiWildcard(ident);
default:
throw new IllegalArgumentException("unknown network template");
}
}
/**
* Check if mobile network with matching IMSI.
*/
private boolean matchesMobile(NetworkIdentity ident) {
if (ident.mType == TYPE_WIMAX) {
// TODO: consider matching against WiMAX subscriber identity
return true;
} else {
return ((sForceAllNetworkTypes || contains(DATA_USAGE_NETWORK_TYPES, ident.mType))
&& Objects.equal(mSubscriberId, ident.mSubscriberId));
}
}
/**
* Check if mobile network classified 3G or lower with matching IMSI.
*/
private boolean matchesMobile3gLower(NetworkIdentity ident) {
ensureSubtypeAvailable();
if (ident.mType == TYPE_WIMAX) {
return false;
} else if (matchesMobile(ident)) {
switch (getNetworkClass(ident.mSubType)) {
case 0:
case 1:
case 2:
return true;
}
}
return false;
}
/**
* Check if mobile network classified 4G with matching IMSI.
*/
private boolean matchesMobile4g(NetworkIdentity ident) {
ensureSubtypeAvailable();
if (ident.mType == TYPE_WIMAX) {
// TODO: consider matching against WiMAX subscriber identity
return true;
} else if (matchesMobile(ident)) {
switch (getNetworkClass(ident.mSubType)) {
case 3:
return true;
}
}
return false;
}
/**
* Check if matches Wi-Fi network template.
*/
private boolean matchesWifi(NetworkIdentity ident) {
switch (ident.mType) {
case TYPE_WIFI:
return Objects.equal(mNetworkId, ident.mNetworkId);
default:
return false;
}
}
/**
* Check if matches Ethernet network template.
*/
private boolean matchesEthernet(NetworkIdentity ident) {
if (ident.mType == TYPE_ETHERNET) {
return true;
}
return false;
}
private boolean matchesMobileWildcard(NetworkIdentity ident) {
if (ident.mType == TYPE_WIMAX) {
return true;
} else {
return sForceAllNetworkTypes || contains(DATA_USAGE_NETWORK_TYPES, ident.mType);
}
}
private boolean matchesWifiWildcard(NetworkIdentity ident) {
switch (ident.mType) {
case TYPE_WIFI:
case 13:
return true;
default:
return false;
}
}
private static String getMatchRuleName(int matchRule) {
switch (matchRule) {
case MATCH_MOBILE_3G_LOWER:
return "MOBILE_3G_LOWER";
case MATCH_MOBILE_4G:
return "MOBILE_4G";
case MATCH_MOBILE_ALL:
return "MOBILE_ALL";
case MATCH_WIFI:
return "WIFI";
case MATCH_ETHERNET:
return "ETHERNET";
case MATCH_MOBILE_WILDCARD:
return "MOBILE_WILDCARD";
case MATCH_WIFI_WILDCARD:
return "WIFI_WILDCARD";
default:
return "UNKNOWN";
}
}
private static void ensureSubtypeAvailable() {
if (COMBINE_SUBTYPE_ENABLED) {
throw new IllegalArgumentException(
"Unable to enforce 3G_LOWER template on combined data.");
}
}
public static final Creator<NetworkTemplate> CREATOR = new Creator<NetworkTemplate>() {
@Override
public NetworkTemplate createFromParcel(Parcel in) {
return new NetworkTemplate(in);
}
@Override
public NetworkTemplate[] newArray(int size) {
return new NetworkTemplate[size];
}
};
}
@@ -0,0 +1,307 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.util.Log;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
/**
* Native methods for managing network interfaces.
* <p/>
* {@hide}
*/
public class NetworkUtils {
private static final String TAG = "NetworkUtils";
/**
* Bring the named network interface up.
*/
public native static int enableInterface(String interfaceName);
/**
* Bring the named network interface down.
*/
public native static int disableInterface(String interfaceName);
/**
* Setting bit 0 indicates reseting of IPv4 addresses required
*/
public static final int RESET_IPV4_ADDRESSES = 0x01;
/**
* Setting bit 1 indicates reseting of IPv4 addresses required
*/
public static final int RESET_IPV6_ADDRESSES = 0x02;
/**
* Reset all addresses
*/
public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
/**
* Reset IPv6 or IPv4 sockets that are connected via the named interface.
*
* @param interfaceName is the interface to reset
* @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
*/
public native static int resetConnections(String interfaceName, int mask);
/**
* Start the DHCP client daemon, in order to have it request addresses
* for the named interface, and then configure the interface with those
* addresses. This call blocks until it obtains a result (either success
* or failure) from the daemon.
*
* @param interfaceName the name of the interface to configure
* @param ipInfo if the request succeeds, this object is filled in with
* the IP address information.
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean runDhcp(String interfaceName, DhcpInfoInternal ipInfo);
/**
* Initiate renewal on the Dhcp client daemon. This call blocks until it obtains
* a result (either success or failure) from the daemon.
*
* @param interfaceName the name of the interface to configure
* @param ipInfo if the request succeeds, this object is filled in with
* the IP address information.
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean runDhcpRenew(String interfaceName, DhcpInfoInternal ipInfo);
/**
* Shut down the DHCP client daemon.
*
* @param interfaceName the name of the interface for which the daemon
* should be stopped
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean stopDhcp(String interfaceName);
/**
* Release the current DHCP lease.
*
* @param interfaceName the name of the interface for which the lease should
* be released
* @return {@code true} for success, {@code false} for failure
*/
public native static boolean releaseDhcpLease(String interfaceName);
/**
* Return the last DHCP-related error message that was recorded.
* <p/>NOTE: This string is not localized, but currently it is only
* used in logging.
*
* @return the most recent error message, if any
*/
public native static String getDhcpError();
/**
* Convert a IPv4 address from an integer to an InetAddress.
*
* @param hostAddress an int corresponding to the IPv4 address in network byte order
*/
public static InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = {(byte) (0xff & hostAddress),
(byte) (0xff & (hostAddress >> 8)),
(byte) (0xff & (hostAddress >> 16)),
(byte) (0xff & (hostAddress >> 24))};
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
/**
* Convert a IPv4 address from an InetAddress to an integer
*
* @param inetAddr is an InetAddress corresponding to the IPv4 address
* @return the IP address as an integer in network byte order
*/
public static int inetAddressToInt(InetAddress inetAddr)
throws IllegalArgumentException {
byte[] addr = inetAddr.getAddress();
if (addr.length != 4) {
throw new IllegalArgumentException("Not an IPv4 address");
}
return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
}
/**
* Convert a network prefix length to an IPv4 netmask integer
*
* @param prefixLength
* @return the IPv4 netmask as an integer in network byte order
*/
public static int prefixLengthToNetmaskInt(int prefixLength)
throws IllegalArgumentException {
if (prefixLength < 0 || prefixLength > 32) {
throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
}
int value = 0xffffffff << (32 - prefixLength);
return Integer.reverseBytes(value);
}
/**
* Convert a IPv4 netmask integer to a prefix length
*
* @param netmask as an integer in network byte order
* @return the network prefix length
*/
public static int netmaskIntToPrefixLength(int netmask) {
return Integer.bitCount(netmask);
}
/**
* Create an InetAddress from a string where the string must be a standard
* representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
* but it will throw an IllegalArgumentException in that case.
*
* @param addrString
* @return the InetAddress
* @hide
*/
public static InetAddress numericToInetAddress(String addrString)
throws IllegalArgumentException {
return null;
}
/**
* Get InetAddress masked with prefixLength. Will never return null.
*
* @param IP address which will be masked with specified prefixLength
* @param prefixLength the prefixLength used to mask the IP
*/
public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
if (address == null) {
throw new RuntimeException("getNetworkPart doesn't accept null address");
}
byte[] array = address.getAddress();
if (prefixLength < 0 || prefixLength > array.length * 8) {
throw new RuntimeException("getNetworkPart - bad prefixLength");
}
int offset = prefixLength / 8;
int reminder = prefixLength % 8;
byte mask = (byte) (0xFF << (8 - reminder));
if (offset < array.length) array[offset] = (byte) (array[offset] & mask);
offset++;
for (; offset < array.length; offset++) {
array[offset] = 0;
}
InetAddress netPart = null;
try {
netPart = InetAddress.getByAddress(array);
} catch (UnknownHostException e) {
throw new RuntimeException("getNetworkPart error - " + e.toString());
}
return netPart;
}
/**
* Check if IP address type is consistent between two InetAddress.
*
* @return true if both are the same type. False otherwise.
*/
public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
((left instanceof Inet6Address) && (right instanceof Inet6Address)));
}
/**
* Convert a 32 char hex string into a Inet6Address.
* throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
* made into an Inet6Address
*
* @param addrHexString a 32 character hex string representing an IPv6 addr
* @return addr an InetAddress representation for the string
*/
public static InetAddress hexToInet6Address(String addrHexString)
throws IllegalArgumentException {
try {
return numericToInetAddress(String.format("%s:%s:%s:%s:%s:%s:%s:%s",
addrHexString.substring(0, 4), addrHexString.substring(4, 8),
addrHexString.substring(8, 12), addrHexString.substring(12, 16),
addrHexString.substring(16, 20), addrHexString.substring(20, 24),
addrHexString.substring(24, 28), addrHexString.substring(28, 32)));
} catch (Exception e) {
Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
throw new IllegalArgumentException(e);
}
}
/**
* Create a string array of host addresses from a collection of InetAddresses
*
* @param addrs a Collection of InetAddresses
* @return an array of Strings containing their host addresses
*/
public static String[] makeStrings(Collection<InetAddress> addrs) {
String[] result = new String[addrs.size()];
int i = 0;
for (InetAddress addr : addrs) {
result[i++] = addr.getHostAddress();
}
return result;
}
/**
* Trim leading zeros from IPv4 address strings
* Our base libraries will interpret that as octel..
* Must leave non v4 addresses and host names alone.
* For example, 192.168.000.010 -> 192.168.0.10
* TODO - fix base libraries and remove this function
*
* @param addr a string representing an ip addr
* @return a string propertly trimmed
*/
public static String trimV4AddrZeros(String addr) {
if (addr == null) return null;
String[] octets = addr.split("\\.");
if (octets.length != 4) return addr;
StringBuilder builder = new StringBuilder(16);
String result = null;
for (int i = 0; i < 4; i++) {
try {
if (octets[i].length() > 3) return addr;
builder.append(Integer.parseInt(octets[i]));
} catch (NumberFormatException e) {
return addr;
}
if (i < 3) builder.append('.');
}
result = builder.toString();
return result;
}
}
@@ -0,0 +1,222 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.annotation.SuppressLint;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import java.net.InetSocketAddress;
/**
* A container class for the http proxy info
*
* @hide
*/
public class ProxyProperties implements Parcelable {
private String mHost;
private int mPort;
private String mExclusionList;
private String[] mParsedExclusionList;
public ProxyProperties(String host, int port, String exclList) {
mHost = host;
mPort = port;
setExclusionList(exclList);
}
private ProxyProperties(String host, int port, String exclList, String[] parsedExclList) {
mHost = host;
mPort = port;
mExclusionList = exclList;
mParsedExclusionList = parsedExclList;
}
// copy constructor instead of clone
public ProxyProperties(ProxyProperties source) {
if (source != null) {
mHost = source.getHost();
mPort = source.getPort();
mExclusionList = source.getExclusionList();
mParsedExclusionList = source.mParsedExclusionList;
}
}
public InetSocketAddress getSocketAddress() {
InetSocketAddress inetSocketAddress = null;
try {
inetSocketAddress = new InetSocketAddress(mHost, mPort);
} catch (IllegalArgumentException e) {
}
return inetSocketAddress;
}
public String getHost() {
return mHost;
}
public int getPort() {
return mPort;
}
// comma separated
public String getExclusionList() {
return mExclusionList;
}
// comma separated
@SuppressLint("DefaultLocale")
private void setExclusionList(String exclusionList) {
mExclusionList = exclusionList;
if (mExclusionList == null) {
mParsedExclusionList = new String[0];
} else {
String splitExclusionList[] = exclusionList.toLowerCase().split(",");
mParsedExclusionList = new String[splitExclusionList.length * 2];
for (int i = 0; i < splitExclusionList.length; i++) {
String s = splitExclusionList[i].trim();
if (s.startsWith(".")) s = s.substring(1);
mParsedExclusionList[i * 2] = s;
mParsedExclusionList[(i * 2) + 1] = "." + s;
}
}
}
public boolean isExcluded(String url) {
if (TextUtils.isEmpty(url) || mParsedExclusionList == null ||
mParsedExclusionList.length == 0) return false;
Uri u = Uri.parse(url);
String urlDomain = u.getHost();
if (urlDomain == null) return false;
for (int i = 0; i < mParsedExclusionList.length; i += 2) {
if (urlDomain.equals(mParsedExclusionList[i]) ||
urlDomain.endsWith(mParsedExclusionList[i + 1])) {
return true;
}
}
return false;
}
public java.net.Proxy makeProxy() {
java.net.Proxy proxy = java.net.Proxy.NO_PROXY;
if (mHost != null) {
try {
InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort);
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress);
} catch (IllegalArgumentException e) {
}
}
return proxy;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (mHost != null) {
sb.append("[");
sb.append(mHost);
sb.append("] ");
sb.append(Integer.toString(mPort));
if (mExclusionList != null) {
sb.append(" xl=").append(mExclusionList);
}
} else {
sb.append("[ProxyProperties.mHost == null]");
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ProxyProperties)) return false;
ProxyProperties p = (ProxyProperties) o;
if (mExclusionList != null && !mExclusionList.equals(p.getExclusionList())) return false;
if (mHost != null && p.getHost() != null && mHost.equals(p.getHost()) == false) {
return false;
}
if (mHost != null && p.mHost == null) return false;
if (mHost == null && p.mHost != null) return false;
if (mPort != p.mPort) return false;
return true;
}
/**
* Implement the Parcelable interface
*
* @hide
*/
public int describeContents() {
return 0;
}
@Override
/*
* generate hashcode based on significant fields
*/
public int hashCode() {
return ((null == mHost) ? 0 : mHost.hashCode())
+ ((null == mExclusionList) ? 0 : mExclusionList.hashCode())
+ mPort;
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
if (mHost != null) {
dest.writeByte((byte) 1);
dest.writeString(mHost);
dest.writeInt(mPort);
} else {
dest.writeByte((byte) 0);
}
dest.writeString(mExclusionList);
dest.writeStringArray(mParsedExclusionList);
}
/**
* Implement the Parcelable interface.
*
* @hide
*/
public static final Creator<ProxyProperties> CREATOR =
new Creator<ProxyProperties>() {
public ProxyProperties createFromParcel(Parcel in) {
String host = null;
int port = 0;
if (in.readByte() == 1) {
host = in.readString();
port = in.readInt();
}
String exclList = in.readString();
//String[] parsedExclList = in.readStringArray();
ProxyProperties proxyProperties =
new ProxyProperties(host, port, exclList, null);
return proxyProperties;
}
public ProxyProperties[] newArray(int size) {
return new ProxyProperties[size];
}
};
}
@@ -0,0 +1,287 @@
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2015 QK Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
/**
* A simple container for route information.
*
* @hide
*/
public class RouteInfo implements Parcelable {
private static final String TAG = "RouteInfo";
/**
* The IP destination address for this route.
*/
private final LinkAddress mDestination;
/**
* The gateway address for this route.
*/
private final InetAddress mGateway;
private final boolean mIsDefault;
private final boolean mIsHost;
public RouteInfo(LinkAddress destination, InetAddress gateway) {
if (destination == null) {
if (gateway != null) {
if (gateway instanceof Inet4Address) {
try {
destination = new LinkAddress(Inet4Address.getLocalHost(), 0);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
} else {
try {
destination = new LinkAddress(Inet6Address.getLocalHost(), 0);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
}
} else {
// no destination, no gateway. invalid.
throw new RuntimeException("Invalid arguments passed in.");
}
}
if (gateway == null) {
if (destination.getAddress() instanceof Inet4Address) {
try {
gateway = Inet4Address.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
} else {
try {
gateway = Inet6Address.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "exception thrown", e);
}
}
}
mDestination = new LinkAddress(NetworkUtils.getNetworkPart(destination.getAddress(),
destination.getNetworkPrefixLength()), destination.getNetworkPrefixLength());
mGateway = gateway;
mIsDefault = isDefault();
mIsHost = isHost();
}
public RouteInfo(InetAddress gateway) {
this(null, gateway);
}
public static RouteInfo makeHostRoute(InetAddress host) {
return makeHostRoute(host, null);
}
public static RouteInfo makeHostRoute(InetAddress host, InetAddress gateway) {
if (host == null) return null;
if (host instanceof Inet4Address) {
return new RouteInfo(new LinkAddress(host, 32), gateway);
} else {
return new RouteInfo(new LinkAddress(host, 128), gateway);
}
}
private boolean isHost() {
try {
return (mGateway.equals(Inet4Address.getLocalHost()) || mGateway.equals(Inet6Address.getLocalHost()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
return false;
}
}
private boolean isDefault() {
boolean val = false;
if (mGateway != null) {
if (mGateway instanceof Inet4Address) {
val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0);
} else {
val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0);
}
}
return val;
}
public LinkAddress getDestination() {
return mDestination;
}
public InetAddress getGateway() {
return mGateway;
}
public boolean isDefaultRoute() {
return mIsDefault;
}
public boolean isHostRoute() {
return mIsHost;
}
public String toString() {
String val = "";
if (mDestination != null) val = mDestination.toString();
if (mGateway != null) val += " -> " + mGateway.getHostAddress();
return val;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
if (mDestination == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeByteArray(mDestination.getAddress().getAddress());
dest.writeInt(mDestination.getNetworkPrefixLength());
}
if (mGateway == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeByteArray(mGateway.getAddress());
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof RouteInfo)) return false;
RouteInfo target = (RouteInfo) obj;
boolean sameDestination = (mDestination == null) ?
target.getDestination() == null
: mDestination.equals(target.getDestination());
boolean sameAddress = (mGateway == null) ?
target.getGateway() == null
: mGateway.equals(target.getGateway());
return sameDestination && sameAddress
&& mIsDefault == target.mIsDefault;
}
@Override
public int hashCode() {
return (mDestination == null ? 0 : mDestination.hashCode())
+ (mGateway == null ? 0 : mGateway.hashCode())
+ (mIsDefault ? 3 : 7);
}
public static final Creator<RouteInfo> CREATOR =
new Creator<RouteInfo>() {
public RouteInfo createFromParcel(Parcel in) {
InetAddress destAddr = null;
int prefix = 0;
InetAddress gateway = null;
if (in.readByte() == 1) {
byte[] addr = in.createByteArray();
prefix = in.readInt();
try {
destAddr = InetAddress.getByAddress(addr);
} catch (UnknownHostException e) {
}
}
if (in.readByte() == 1) {
byte[] addr = in.createByteArray();
try {
gateway = InetAddress.getByAddress(addr);
} catch (UnknownHostException e) {
}
}
LinkAddress dest = null;
if (destAddr != null) {
dest = new LinkAddress(destAddr, prefix);
}
return new RouteInfo(dest, gateway);
}
public RouteInfo[] newArray(int size) {
return new RouteInfo[size];
}
};
private boolean matches(InetAddress destination) {
if (destination == null) return false;
// if the destination is present and the route is default.
// return true
if (isDefault()) return true;
// match the route destination and destination with prefix length
InetAddress dstNet = NetworkUtils.getNetworkPart(destination,
mDestination.getNetworkPrefixLength());
return mDestination.getAddress().equals(dstNet);
}
/**
* Find the route from a Collection of routes that best matches a given address.
* May return null if no routes are applicable.
*
* @param routes a Collection of RouteInfos to chose from
* @param dest the InetAddress your trying to get to
* @return the RouteInfo from the Collection that best fits the given address
*/
public static RouteInfo selectBestRoute(Collection<RouteInfo> routes, InetAddress dest) {
if ((routes == null) || (dest == null)) return null;
RouteInfo bestRoute = null;
// pick a longest prefix match under same address type
for (RouteInfo route : routes) {
if (NetworkUtils.addressTypeMatches(route.mDestination.getAddress(), dest)) {
if ((bestRoute != null) &&
(bestRoute.mDestination.getNetworkPrefixLength() >=
route.mDestination.getNetworkPrefixLength())) {
continue;
}
if (route.matches(dest)) bestRoute = route;
}
}
return bestRoute;
}
}
@@ -0,0 +1,835 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.provider;
import android.app.DownloadManager;
import android.content.Context;
import android.net.NetworkPolicyManager;
import android.net.Uri;
/**
* The Download Manager
*
* @pending
*/
public final class Downloads {
private Downloads() {
}
/**
* Implementation details
* <p/>
* Exposes constants used to interact with the download manager's
* content provider.
* The constants URI ... STATUS are the names of columns in the downloads table.
*
* @hide
*/
public static final class Impl implements BaseColumns {
private Impl() {
}
/**
* The permission to access the download manager
*/
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER";
/**
* The permission to access the download manager's advanced functions
*/
public static final String PERMISSION_ACCESS_ADVANCED =
"android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED";
/**
* The permission to access the all the downloads in the manager.
*/
public static final String PERMISSION_ACCESS_ALL =
"android.permission.ACCESS_ALL_DOWNLOADS";
/**
* The permission to directly access the download manager's cache
* directory
*/
public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM";
/**
* The permission to send broadcasts on download completion
*/
public static final String PERMISSION_SEND_INTENTS =
"android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS";
/**
* The permission to download files to the cache partition that won't be automatically
* purged when space is needed.
*/
public static final String PERMISSION_CACHE_NON_PURGEABLE =
"android.permission.DOWNLOAD_CACHE_NON_PURGEABLE";
/**
* The permission to download files without any system notification being shown.
*/
public static final String PERMISSION_NO_NOTIFICATION =
"android.permission.DOWNLOAD_WITHOUT_NOTIFICATION";
/**
* The content:// URI to access downloads owned by the caller's UID.
*/
public static final Uri CONTENT_URI =
Uri.parse("content://downloads/my_downloads");
/**
* The content URI for accessing all downloads across all UIDs (requires the
* ACCESS_ALL_DOWNLOADS permission).
*/
public static final Uri ALL_DOWNLOADS_CONTENT_URI =
Uri.parse("content://downloads/all_downloads");
/**
* URI segment to access a publicly accessible downloaded file
*/
public static final String PUBLICLY_ACCESSIBLE_DOWNLOADS_URI_SEGMENT = "public_downloads";
/**
* The content URI for accessing publicly accessible downloads (i.e., it requires no
* permissions to access this downloaded file)
*/
public static final Uri PUBLICLY_ACCESSIBLE_DOWNLOADS_URI =
Uri.parse("content://downloads/" + PUBLICLY_ACCESSIBLE_DOWNLOADS_URI_SEGMENT);
/**
* Broadcast Action: this is sent by the download manager to the app
* that had initiated a download when that download completes. The
* download's content: uri is specified in the intent's data.
*/
public static final String ACTION_DOWNLOAD_COMPLETED =
"android.intent.action.DOWNLOAD_COMPLETED";
/**
* Broadcast Action: this is sent by the download manager to the app
* that had initiated a download when the user selects the notification
* associated with that download. The download's content: uri is specified
* in the intent's data if the click is associated with a single download,
* or Downloads.CONTENT_URI if the notification is associated with
* multiple downloads.
* Note: this is not currently sent for downloads that have completed
* successfully.
*/
public static final String ACTION_NOTIFICATION_CLICKED =
"android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
/**
* The name of the column containing the URI of the data being downloaded.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_URI = "uri";
/**
* The name of the column containing application-specific data.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_APP_DATA = "entity";
/**
* The name of the column containing the flags that indicates whether
* the initiating application is capable of verifying the integrity of
* the downloaded file. When this flag is set, the download manager
* performs downloads and reports success even in some situations where
* it can't guarantee that the download has completed (e.g. when doing
* a byte-range request without an ETag, or when it can't determine
* whether a download fully completed).
* <P>Type: BOOLEAN</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_NO_INTEGRITY = "no_integrity";
/**
* The name of the column containing the filename that the initiating
* application recommends. When possible, the download manager will attempt
* to use this filename, or a variation, as the actual name for the file.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_FILE_NAME_HINT = "hint";
/**
* The name of the column containing the filename where the downloaded data
* was actually stored.
* <P>Type: TEXT</P>
* <P>Owner can Read</P>
*/
public static final String _DATA = "_data";
/**
* The name of the column containing the MIME type of the downloaded data.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_MIME_TYPE = "mimetype";
/**
* The name of the column containing the flag that controls the destination
* of the download. See the DESTINATION_* constants for a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_DESTINATION = "destination";
/**
* The name of the column containing the flags that controls whether the
* download is displayed by the UI. See the VISIBILITY_* constants for
* a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_VISIBILITY = "visibility";
/**
* The name of the column containing the current control state of the download.
* Applications can write to this to control (pause/resume) the download.
* the CONTROL_* constants for a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_CONTROL = "control";
/**
* The name of the column containing the current status of the download.
* Applications can read this to follow the progress of each download. See
* the STATUS_* constants for a list of legal values.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_STATUS = "status";
/**
* The name of the column containing the date at which some interesting
* status changed in the download. Stored as a System.currentTimeMillis()
* value.
* <P>Type: BIGINT</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_LAST_MODIFICATION = "lastmod";
/**
* The name of the column containing the package name of the application
* that initiating the download. The download manager will send
* notifications to a component in this package when the download completes.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage";
/**
* The name of the column containing the component name of the class that
* will receive notifications associated with the download. The
* package/class combination is passed to
* Intent.setClassName(String,String).
* <P>Type: TEXT</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass";
/**
* If extras are specified when requesting a download they will be provided in the intent that
* is sent to the specified class and package when a download has finished.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras";
/**
* The name of the column contain the values of the cookie to be used for
* the download. This is used directly as the value for the Cookie: HTTP
* header that gets sent with the request.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_COOKIE_DATA = "cookiedata";
/**
* The name of the column containing the user agent that the initiating
* application wants the download manager to use for this download.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_USER_AGENT = "useragent";
/**
* The name of the column containing the referer (sic) that the initiating
* application wants the download manager to use for this download.
* <P>Type: TEXT</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_REFERER = "referer";
/**
* The name of the column containing the total size of the file being
* downloaded.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_TOTAL_BYTES = "total_bytes";
/**
* The name of the column containing the size of the part of the file that
* has been downloaded so far.
* <P>Type: INTEGER</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_CURRENT_BYTES = "current_bytes";
/**
* The name of the column where the initiating application can provide the
* UID of another application that is allowed to access this download. If
* multiple applications share the same UID, all those applications will be
* allowed to access this download. This column can be updated after the
* download is initiated. This requires the permission
* android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED.
* <P>Type: INTEGER</P>
* <P>Owner can Init</P>
*/
public static final String COLUMN_OTHER_UID = "otheruid";
/**
* The name of the column where the initiating application can provided the
* title of this download. The title will be displayed ito the user in the
* list of downloads.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_TITLE = "title";
/**
* The name of the column where the initiating application can provide the
* description of this download. The description will be displayed to the
* user in the list of downloads.
* <P>Type: TEXT</P>
* <P>Owner can Init/Read/Write</P>
*/
public static final String COLUMN_DESCRIPTION = "description";
/**
* The name of the column indicating whether the download was requesting through the public
* API. This controls some differences in behavior.
* <P>Type: BOOLEAN</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_IS_PUBLIC_API = "is_public_api";
/**
* The name of the column holding a bitmask of allowed network types. This is only used for
* public API downloads.
* <P>Type: INTEGER</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_ALLOWED_NETWORK_TYPES = "allowed_network_types";
/**
* The name of the column indicating whether roaming connections can be used. This is only
* used for public API downloads.
* <P>Type: BOOLEAN</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_ALLOW_ROAMING = "allow_roaming";
/**
* The name of the column indicating whether metered connections can be used. This is only
* used for public API downloads.
* <P>Type: BOOLEAN</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_ALLOW_METERED = "allow_metered";
/**
* Whether or not this download should be displayed in the system's Downloads UI. Defaults
* to true.
* <P>Type: INTEGER</P>
* <P>Owner can Init/Read</P>
*/
public static final String COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI = "is_visible_in_downloads_ui";
/**
* If true, the user has confirmed that this download can proceed over the mobile network
* even though it exceeds the recommended maximum size.
* <P>Type: BOOLEAN</P>
*/
public static final String COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT =
"bypass_recommended_size_limit";
/**
* Set to true if this download is deleted. It is completely removed from the database
* when MediaProvider database also deletes the metadata asociated with this downloaded file.
* <P>Type: BOOLEAN</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_DELETED = "deleted";
/**
* The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
* used to delete the entries from MediaProvider database when it is deleted from the
* downloaded list.
* <P>Type: TEXT</P>
* <P>Owner can Read</P>
*/
public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri";
/**
* The column that is used to remember whether the media scanner was invoked.
* It can take the values: null or 0(not scanned), 1(scanned), 2 (not scannable).
* <P>Type: TEXT</P>
*/
public static final String COLUMN_MEDIA_SCANNED = "scanned";
/**
* The column with errorMsg for a failed downloaded.
* Used only for debugging purposes.
* <P>Type: TEXT</P>
*/
public static final String COLUMN_ERROR_MSG = "errorMsg";
/**
* This column stores the source of the last update to this row.
* This column is only for internal use.
* Valid values are indicated by LAST_UPDATESRC_* constants.
* <P>Type: INT</P>
*/
public static final String COLUMN_LAST_UPDATESRC = "lastUpdateSrc";
/**
* default value for {@link #COLUMN_LAST_UPDATESRC}.
* This value is used when this column's value is not relevant.
*/
public static final int LAST_UPDATESRC_NOT_RELEVANT = 0;
/**
* One of the values taken by {@link #COLUMN_LAST_UPDATESRC}.
* This value is used when the update is NOT to be relayed to the DownloadService
* (and thus spare DownloadService from scanning the database when this change occurs)
*/
public static final int LAST_UPDATESRC_DONT_NOTIFY_DOWNLOADSVC = 1;
/*
* Lists the destinations that an application can specify for a download.
*/
/**
* This download will be saved to the external storage. This is the
* default behavior, and should be used for any file that the user
* can freely access, copy, delete. Even with that destination,
* unencrypted DRM files are saved in secure internal storage.
* Downloads to the external destination only write files for which
* there is a registered handler. The resulting files are accessible
* by filename to all applications.
*/
public static final int DESTINATION_EXTERNAL = 0;
/**
* This download will be saved to the download manager's private
* partition. This is the behavior used by applications that want to
* download private files that are used and deleted soon after they
* get downloaded. All file types are allowed, and only the initiating
* application can access the file (indirectly through a content
* provider). This requires the
* android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED permission.
*/
public static final int DESTINATION_CACHE_PARTITION = 1;
/**
* This download will be saved to the download manager's private
* partition and will be purged as necessary to make space. This is
* for private files (similar to CACHE_PARTITION) that aren't deleted
* immediately after they are used, and are kept around by the download
* manager as long as space is available.
*/
public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2;
/**
* This download will be saved to the download manager's private
* partition, as with DESTINATION_CACHE_PARTITION, but the download
* will not proceed if the user is on a roaming data connection.
*/
public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3;
/**
* This download will be saved to the location given by the file URI in
* {@link #COLUMN_FILE_NAME_HINT}.
*/
public static final int DESTINATION_FILE_URI = 4;
/**
* This download will be saved to the system cache ("/cache")
* partition. This option is only used by system apps and so it requires
* android.permission.ACCESS_CACHE_FILESYSTEM permission.
*/
public static final int DESTINATION_SYSTEMCACHE_PARTITION = 5;
/**
* This download was completed by the caller (i.e., NOT downloadmanager)
* and caller wants to have this download displayed in Downloads App.
*/
public static final int DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD = 6;
/**
* This download is allowed to run.
*/
public static final int CONTROL_RUN = 0;
/**
* This download must pause at the first opportunity.
*/
public static final int CONTROL_PAUSED = 1;
/*
* Lists the states that the download manager can set on a download
* to notify applications of the download progress.
* The codes follow the HTTP families:<br>
* 1xx: informational<br>
* 2xx: success<br>
* 3xx: redirects (not used by the download manager)<br>
* 4xx: client errors<br>
* 5xx: server errors
*/
/**
* Returns whether the status is informational (i.e. 1xx).
*/
public static boolean isStatusInformational(int status) {
return (status >= 100 && status < 200);
}
/**
* Returns whether the status is a success (i.e. 2xx).
*/
public static boolean isStatusSuccess(int status) {
return (status >= 200 && status < 300);
}
/**
* Returns whether the status is an error (i.e. 4xx or 5xx).
*/
public static boolean isStatusError(int status) {
return (status >= 400 && status < 600);
}
/**
* Returns whether the status is a client error (i.e. 4xx).
*/
public static boolean isStatusClientError(int status) {
return (status >= 400 && status < 500);
}
/**
* Returns whether the status is a server error (i.e. 5xx).
*/
public static boolean isStatusServerError(int status) {
return (status >= 500 && status < 600);
}
/**
* this method determines if a notification should be displayed for a
* given {@link #COLUMN_VISIBILITY} value
*
* @param visibility the value of {@link #COLUMN_VISIBILITY}.
* @return true if the notification should be displayed. false otherwise.
*/
public static boolean isNotificationToBeDisplayed(int visibility) {
return visibility == DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ||
visibility == DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION;
}
/**
* Returns whether the download has completed (either with success or
* error).
*/
public static boolean isStatusCompleted(int status) {
return (status >= 200 && status < 300) || (status >= 400 && status < 600);
}
/**
* This download hasn't stated yet
*/
public static final int STATUS_PENDING = 190;
/**
* This download has started
*/
public static final int STATUS_RUNNING = 192;
/**
* This download has been paused by the owning app.
*/
public static final int STATUS_PAUSED_BY_APP = 193;
/**
* This download encountered some network error and is waiting before retrying the request.
*/
public static final int STATUS_WAITING_TO_RETRY = 194;
/**
* This download is waiting for network connectivity to proceed.
*/
public static final int STATUS_WAITING_FOR_NETWORK = 195;
/**
* This download exceeded a size limit for mobile networks and is waiting for a Wi-Fi
* connection to proceed.
*/
public static final int STATUS_QUEUED_FOR_WIFI = 196;
/**
* This download couldn't be completed due to insufficient storage
* space. Typically, this is because the SD card is full.
*/
public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 198;
/**
* This download couldn't be completed because no external storage
* device was found. Typically, this is because the SD card is not
* mounted.
*/
public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 199;
/**
* This download has successfully completed.
* Warning: there might be other status values that indicate success
* in the future.
* Use isSucccess() to capture the entire category.
*/
public static final int STATUS_SUCCESS = 200;
/**
* This request couldn't be parsed. This is also used when processing
* requests with unknown/unsupported URI schemes.
*/
public static final int STATUS_BAD_REQUEST = 400;
/**
* This download can't be performed because the content type cannot be
* handled.
*/
public static final int STATUS_NOT_ACCEPTABLE = 406;
/**
* This download cannot be performed because the length cannot be
* determined accurately. This is the code for the HTTP error "Length
* Required", which is typically used when making requests that require
* a content length but don't have one, and it is also used in the
* client when a response is received whose length cannot be determined
* accurately (therefore making it impossible to know when a download
* completes).
*/
public static final int STATUS_LENGTH_REQUIRED = 411;
/**
* This download was interrupted and cannot be resumed.
* This is the code for the HTTP error "Precondition Failed", and it is
* also used in situations where the client doesn't have an ETag at all.
*/
public static final int STATUS_PRECONDITION_FAILED = 412;
/**
* The lowest-valued error status that is not an actual HTTP status code.
*/
public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488;
/**
* The requested destination file already exists.
*/
public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488;
/**
* Some possibly transient error occurred, but we can't resume the download.
*/
public static final int STATUS_CANNOT_RESUME = 489;
/**
* This download was canceled
*/
public static final int STATUS_CANCELED = 490;
/**
* This download has completed with an error.
* Warning: there will be other status values that indicate errors in
* the future. Use isStatusError() to capture the entire category.
*/
public static final int STATUS_UNKNOWN_ERROR = 491;
/**
* This download couldn't be completed because of a storage issue.
* Typically, that's because the filesystem is missing or full.
* Use the more specific {@link #STATUS_INSUFFICIENT_SPACE_ERROR}
* and {@link #STATUS_DEVICE_NOT_FOUND_ERROR} when appropriate.
*/
public static final int STATUS_FILE_ERROR = 492;
/**
* This download couldn't be completed because of an HTTP
* redirect response that the download manager couldn't
* handle.
*/
public static final int STATUS_UNHANDLED_REDIRECT = 493;
/**
* This download couldn't be completed because of an
* unspecified unhandled HTTP code.
*/
public static final int STATUS_UNHANDLED_HTTP_CODE = 494;
/**
* This download couldn't be completed because of an
* error receiving or processing data at the HTTP level.
*/
public static final int STATUS_HTTP_DATA_ERROR = 495;
/**
* This download couldn't be completed because of an
* HttpException while setting up the request.
*/
public static final int STATUS_HTTP_EXCEPTION = 496;
/**
* This download couldn't be completed because there were
* too many redirects.
*/
public static final int STATUS_TOO_MANY_REDIRECTS = 497;
/**
* This download has failed because requesting application has been
* blocked by {@link NetworkPolicyManager}.
*
* @hide
* @deprecated since behavior now uses
* {@link #STATUS_WAITING_FOR_NETWORK}
*/
@Deprecated
public static final int STATUS_BLOCKED = 498;
/**
* {@hide}
*/
public static String statusToString(int status) {
switch (status) {
case STATUS_PENDING:
return "PENDING";
case STATUS_RUNNING:
return "RUNNING";
case STATUS_PAUSED_BY_APP:
return "PAUSED_BY_APP";
case STATUS_WAITING_TO_RETRY:
return "WAITING_TO_RETRY";
case STATUS_WAITING_FOR_NETWORK:
return "WAITING_FOR_NETWORK";
case STATUS_QUEUED_FOR_WIFI:
return "QUEUED_FOR_WIFI";
case STATUS_INSUFFICIENT_SPACE_ERROR:
return "INSUFFICIENT_SPACE_ERROR";
case STATUS_DEVICE_NOT_FOUND_ERROR:
return "DEVICE_NOT_FOUND_ERROR";
case STATUS_SUCCESS:
return "SUCCESS";
case STATUS_BAD_REQUEST:
return "BAD_REQUEST";
case STATUS_NOT_ACCEPTABLE:
return "NOT_ACCEPTABLE";
case STATUS_LENGTH_REQUIRED:
return "LENGTH_REQUIRED";
case STATUS_PRECONDITION_FAILED:
return "PRECONDITION_FAILED";
case STATUS_FILE_ALREADY_EXISTS_ERROR:
return "FILE_ALREADY_EXISTS_ERROR";
case STATUS_CANNOT_RESUME:
return "CANNOT_RESUME";
case STATUS_CANCELED:
return "CANCELED";
case STATUS_UNKNOWN_ERROR:
return "UNKNOWN_ERROR";
case STATUS_FILE_ERROR:
return "FILE_ERROR";
case STATUS_UNHANDLED_REDIRECT:
return "UNHANDLED_REDIRECT";
case STATUS_UNHANDLED_HTTP_CODE:
return "UNHANDLED_HTTP_CODE";
case STATUS_HTTP_DATA_ERROR:
return "HTTP_DATA_ERROR";
case STATUS_HTTP_EXCEPTION:
return "HTTP_EXCEPTION";
case STATUS_TOO_MANY_REDIRECTS:
return "TOO_MANY_REDIRECTS";
case STATUS_BLOCKED:
return "BLOCKED";
default:
return Integer.toString(status);
}
}
/**
* This download is visible but only shows in the notifications
* while it's in progress.
*/
public static final int VISIBILITY_VISIBLE = DownloadManager.Request.VISIBILITY_VISIBLE;
/**
* This download is visible and shows in the notifications while
* in progress and after completion.
*/
public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED =
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED;
/**
* This download doesn't show in the UI or in the notifications.
*/
public static final int VISIBILITY_HIDDEN = DownloadManager.Request.VISIBILITY_HIDDEN;
/**
* Constants related to HTTP request headers associated with each download.
*/
public static class RequestHeaders {
public static final String HEADERS_DB_TABLE = "request_headers";
public static final String COLUMN_DOWNLOAD_ID = "download_id";
public static final String COLUMN_HEADER = "header";
public static final String COLUMN_VALUE = "value";
/**
* Path segment to add to a download URI to retrieve request headers
*/
public static final String URI_SEGMENT = "headers";
/**
* Prefix for ContentValues keys that contain HTTP header lines, to be passed to
* DownloadProvider.insert().
*/
public static final String INSERT_KEY_PREFIX = "http_header_";
}
}
/**
* Query where clause for general querying.
*/
private static final String QUERY_WHERE_CLAUSE = Impl.COLUMN_NOTIFICATION_PACKAGE + "=? AND "
+ Impl.COLUMN_NOTIFICATION_CLASS + "=?";
/**
* Delete all the downloads for a package/class pair.
*/
public static final void removeAllDownloadsByPackage(
Context context, String notification_package, String notification_class) {
context.getContentResolver().delete(Impl.CONTENT_URI, QUERY_WHERE_CLAUSE,
new String[]{notification_package, notification_class});
}
}