Merge pull request #594 from Inhishonor/upgrade-smsmms-group-individual-send-no-wait-appear-delayed-mms-mms-receive-to-worker-send-ack-mmsc

Upgrade smsmms group individual send no wait appear delayed mms mms receive to worker send ack mmsc
This commit is contained in:
octoshrimpy
2025-12-09 21:51:39 -05:00
committed by GitHub
359 changed files with 20432 additions and 3917 deletions
-1
View File
@@ -27,7 +27,6 @@ android {
targetSdkVersion 33 targetSdkVersion 33
} }
useLibrary 'org.apache.http.legacy' useLibrary 'org.apache.http.legacy'
lint { lint {
abortOnError false abortOnError false
+18
View File
@@ -0,0 +1,18 @@
VERSION_NAME=5.2.6
VERSION_CODE=76
GROUP=com.klinkerapps
POM_DESCRIPTION=Android Messaging library for SMS and MMS
POM_URL=https://github.com/klinker41/android-smsmms
POM_SCM_URL=https://github.com/klinker41/android-smsmms
POM_SCM_CONNECTION=scm:git@github.com:klinker41/android-smsmms.git
POM_SCM_DEV_CONNECTION=scm:git@github.com:klinker41/android-smsmms.git
POM_LICENCE_NAME=The Apache Software License, Version 2.0
POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo
POM_DEVELOPER_ID=klinker41
POM_DEVELOPER_NAME=Jacob Klinker
POM_NAME=Andorid Messaging
POM_ARTIFACT_ID=android-smsmms
POM_PACKAGING=aar
-21
View File
@@ -1,21 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
+5 -2
View File
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest
package="com.klinker.android.send_message"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application> <application>
<provider android:name=".MmsFileProvider" <provider android:name=".MmsFileProvider"
@@ -10,5 +11,7 @@
android:grantUriPermissions="true" android:grantUriPermissions="true"
android:exported="false" /> android:exported="false" />
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
</application> </application>
</manifest> </manifest>
@@ -0,0 +1,4 @@
package com.klinker.android.timberworkarounds
fun Timber_isLoggable(tag: String, level: Int): Boolean = true
@@ -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();
}
+18 -7
View File
@@ -22,15 +22,16 @@ import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.widget.Toast;
import org.jetbrains.annotations.Nullable;
import timber.log.Timber; import timber.log.Timber;
import android.widget.Toast;
/** /**
* @hide * @hide
*/ */
public final class SqliteWrapper { public final class SqliteWrapper {
private static final String TAG = "SqliteWrapper";
private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE
= "unable to open database file"; = "unable to open database file";
@@ -52,24 +53,34 @@ public final class SqliteWrapper {
} }
} }
@Nullable
public static Cursor query(Context context, ContentResolver resolver, Uri uri, public static Cursor query(Context context, ContentResolver resolver, Uri uri,
String[] projection, String selection, String[] selectionArgs, String sortOrder) { String[] projection, String selection, String[] selectionArgs, String sortOrder) {
try { try {
return resolver.query(uri, projection, selection, selectionArgs, sortOrder); return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (SQLiteException e) { } catch (SQLiteException e) {
Timber.e(e, "Catch a SQLiteException when query: "); Timber.e("Catch a SQLiteException when query: ", e);
checkSQLiteException(context, e); checkSQLiteException(context, e);
return null; return null;
} }
} }
@SuppressWarnings("deprecation")
public static boolean requery(Context context, Cursor cursor) {
try {
return cursor.requery();
} catch (SQLiteException e) {
Timber.e("Catch a SQLiteException when requery: ", e);
checkSQLiteException(context, e);
return false;
}
}
public static int update(Context context, ContentResolver resolver, Uri uri, public static int update(Context context, ContentResolver resolver, Uri uri,
ContentValues values, String where, String[] selectionArgs) { ContentValues values, String where, String[] selectionArgs) {
try { try {
return resolver.update(uri, values, where, selectionArgs); return resolver.update(uri, values, where, selectionArgs);
} catch (SQLiteException e) { } catch (SQLiteException e) {
Timber.e(e, "Catch a SQLiteException when update: "); Timber.e("Catch a SQLiteException when update: ", e);
checkSQLiteException(context, e); checkSQLiteException(context, e);
return -1; return -1;
} }
@@ -80,7 +91,7 @@ public final class SqliteWrapper {
try { try {
return resolver.delete(uri, where, selectionArgs); return resolver.delete(uri, where, selectionArgs);
} catch (SQLiteException e) { } catch (SQLiteException e) {
Timber.e(e, "Catch a SQLiteException when delete: "); Timber.e("Catch a SQLiteException when delete: ", e);
checkSQLiteException(context, e); checkSQLiteException(context, e);
return -1; return -1;
} }
@@ -91,7 +102,7 @@ public final class SqliteWrapper {
try { try {
return resolver.insert(uri, values); return resolver.insert(uri, values);
} catch (SQLiteException e) { } catch (SQLiteException e) {
Timber.e(e, "Catch a SQLiteException when insert: "); Timber.e("Catch a SQLiteException when insert: ", e);
checkSQLiteException(context, e); checkSQLiteException(context, e);
return null; return null;
} }
@@ -1,167 +0,0 @@
/*
* 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.text.TextUtils;
import timber.log.Timber;
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 {
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 = NetworkUtilsHelper.numericToInetAddress(addr);
if (inetAddress instanceof Inet4Address) {
return NetworkUtilsHelper.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 = NetworkUtilsHelper.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)) {
Timber.e("makeLinkAddress with empty ipAddress");
return null;
}
return new LinkAddress(NetworkUtilsHelper.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(NetworkUtilsHelper.numericToInetAddress(dns1));
} else {
Timber.d("makeLinkProperties with empty dns1!");
}
if (TextUtils.isEmpty(dns2) == false) {
p.addDns(NetworkUtilsHelper.numericToInetAddress(dns2));
} else {
Timber.d("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
View File
@@ -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 java.lang.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;
}
View File
+2 -1
View File
@@ -18,7 +18,7 @@ package android.net;
import android.os.Parcel; import android.os.Parcel;
import android.os.Parcelable; import android.os.Parcelable;
import timber.log.Timber; import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
@@ -32,6 +32,7 @@ import java.util.Set;
* @hide * @hide
*/ */
public class LinkCapabilities implements Parcelable { public class LinkCapabilities implements Parcelable {
private static final String TAG = "LinkCapabilities";
private static final boolean DBG = false; private static final boolean DBG = false;
/** /**
View File
@@ -0,0 +1,227 @@
/*
* 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.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 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,193 @@
/*
* 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;
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,293 @@
/*
* 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.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;
}
/**
* 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("]");
}
}
View File
View File
@@ -0,0 +1,453 @@
/*
* 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;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Objects;
import static android.net.ConnectivityManager.*;
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];
}
};
}
+4 -218
View File
@@ -16,7 +16,7 @@
package android.net; package android.net;
import timber.log.Timber; import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.Inet6Address; import java.net.Inet6Address;
@@ -31,6 +31,8 @@ import java.util.Collection;
*/ */
public class NetworkUtilsHelper { public class NetworkUtilsHelper {
private static final String TAG = "NetworkUtils";
/** /**
* Bring the named network interface up. * Bring the named network interface up.
*/ */
@@ -56,223 +58,6 @@ public class NetworkUtilsHelper {
*/ */
public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_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) {
Timber.e("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 * Trim leading zeros from IPv4 address strings
* Our base libraries will interpret that as octel.. * Our base libraries will interpret that as octel..
@@ -301,4 +86,5 @@ public class NetworkUtilsHelper {
result = builder.toString(); result = builder.toString();
return result; return result;
} }
} }
View File
@@ -1,285 +0,0 @@
/*
* 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;
import timber.log.Timber;
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 {
/**
* 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
Timber.e(e, "exception thrown");
}
} else {
try {
destination = new LinkAddress(Inet6Address.getLocalHost(), 0);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Timber.e(e, "exception thrown");
}
}
} 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
Timber.e(e, "exception thrown");
}
} else {
try {
gateway = Inet6Address.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Timber.e(e, "exception thrown");
}
}
}
mDestination = new LinkAddress(NetworkUtilsHelper.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 = NetworkUtilsHelper.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 (NetworkUtilsHelper.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});
}
}
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2012 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 com.android.internal.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Denotes that the class, method or field has its visibility relaxed so
* that unit tests can access it.
* <p/>
* The <code>visibility</code> argument can be used to specific what the original
* visibility should have been if it had not been made public or package-private for testing.
* The default is to consider the element private.
*/
@Retention(RetentionPolicy.SOURCE)
public @interface VisibleForTesting {
/**
* Intended visibility if the element had not been made public or package-private for
* testing.
*/
enum Visibility {
/**
* The element should be considered protected.
*/
PROTECTED,
/**
* The element should be considered package-private.
*/
PACKAGE,
/**
* The element should be considered private.
*/
PRIVATE
}
/**
* Intended visibility if the element had not been made public or package-private for testing.
* If not specified, one should assume the element originally intended to be private.
*/
Visibility visibility() default Visibility.PRIVATE;
}
@@ -0,0 +1,94 @@
/*
* 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 com.android.internal.net;
import android.app.PendingIntent;
import android.net.NetworkInfo;
import android.os.Parcel;
import android.os.Parcelable;
import timber.log.Timber;
/**
* A simple container used to carry information of the ongoing legacy VPN.
* Internal use only.
*
* @hide
*/
public class LegacyVpnInfo implements Parcelable {
private static final String TAG = "LegacyVpnInfo";
public static final int STATE_DISCONNECTED = 0;
public static final int STATE_INITIALIZING = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public static final int STATE_TIMEOUT = 4;
public static final int STATE_FAILED = 5;
public String key;
public int state = -1;
public PendingIntent intent;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(key);
out.writeInt(state);
out.writeParcelable(intent, flags);
}
public static final Parcelable.Creator<LegacyVpnInfo> CREATOR =
new Parcelable.Creator<LegacyVpnInfo>() {
@Override
public LegacyVpnInfo createFromParcel(Parcel in) {
LegacyVpnInfo info = new LegacyVpnInfo();
info.key = in.readString();
info.state = in.readInt();
info.intent = in.readParcelable(null);
return info;
}
@Override
public LegacyVpnInfo[] newArray(int size) {
return new LegacyVpnInfo[size];
}
};
/**
* Return best matching {@link LegacyVpnInfo} state based on given
* {@link NetworkInfo}.
*/
public static int stateFromNetworkInfo(NetworkInfo info) {
switch (info.getDetailedState()) {
case CONNECTING:
return STATE_CONNECTING;
case CONNECTED:
return STATE_CONNECTED;
case DISCONNECTED:
return STATE_DISCONNECTED;
case FAILED:
return STATE_FAILED;
default:
Timber.w("Unhandled state " + info.getDetailedState()
+ " ; treating as disconnected");
return STATE_DISCONNECTED;
}
}
}
@@ -0,0 +1,115 @@
/*
* 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 com.android.internal.net;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.util.Preconditions;
import java.util.List;
/**
* A simple container used to carry information in VpnBuilder, VpnDialogs,
* and com.android.server.connectivity.Vpn. Internal use only.
*
* @hide
*/
public class VpnConfig implements Parcelable {
public static final String SERVICE_INTERFACE = "android.net.VpnService";
public static final String DIALOGS_PACKAGE = "com.android.vpndialogs";
public static final String LEGACY_VPN = "[Legacy VPN]";
public static Intent getIntentForConfirmation() {
Intent intent = new Intent();
intent.setClassName(DIALOGS_PACKAGE, DIALOGS_PACKAGE + ".ConfirmDialog");
return intent;
}
public static PendingIntent getIntentForStatusPanel(Context context, VpnConfig config) {
Preconditions.checkNotNull(config);
Intent intent = new Intent();
intent.setClassName(DIALOGS_PACKAGE, DIALOGS_PACKAGE + ".ManageDialog");
intent.putExtra("config", config);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_MUTABLE);
}
public String user;
public String interfaze;
public String session;
public int mtu = -1;
public String addresses;
public String routes;
public List<String> dnsServers;
public List<String> searchDomains;
public PendingIntent configureIntent;
public long startTime = -1;
public boolean legacy;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(user);
out.writeString(interfaze);
out.writeString(session);
out.writeInt(mtu);
out.writeString(addresses);
out.writeString(routes);
out.writeStringList(dnsServers);
out.writeStringList(searchDomains);
out.writeParcelable(configureIntent, flags);
out.writeLong(startTime);
out.writeInt(legacy ? 1 : 0);
}
public static final Parcelable.Creator<VpnConfig> CREATOR =
new Parcelable.Creator<VpnConfig>() {
@Override
public VpnConfig createFromParcel(Parcel in) {
VpnConfig config = new VpnConfig();
config.user = in.readString();
config.interfaze = in.readString();
config.session = in.readString();
config.mtu = in.readInt();
config.addresses = in.readString();
config.routes = in.readString();
config.dnsServers = in.createStringArrayList();
config.searchDomains = in.createStringArrayList();
config.configureIntent = in.readParcelable(null);
config.startTime = in.readLong();
config.legacy = in.readInt() != 0;
return config;
}
@Override
public VpnConfig[] newArray(int size) {
return new VpnConfig[size];
}
};
}
@@ -0,0 +1,202 @@
/*
* 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 com.android.internal.net;
import android.os.Parcel;
import android.os.Parcelable;
import timber.log.Timber;
import java.nio.charset.Charset;
/**
* Parcel-like entity class for VPN profiles. To keep things simple, all
* fields are package private. Methods are provided for serialization, so
* storage can be implemented easily. Two rules are set for this class.
* First, all fields must be kept non-null. Second, always make a copy
* using clone() before modifying.
*
* @hide
*/
public class VpnProfile implements Cloneable, Parcelable {
private static final String TAG = "VpnProfile";
// Match these constants with R.array.vpn_types.
public static final int TYPE_PPTP = 0;
public static final int TYPE_L2TP_IPSEC_PSK = 1;
public static final int TYPE_L2TP_IPSEC_RSA = 2;
public static final int TYPE_IPSEC_XAUTH_PSK = 3;
public static final int TYPE_IPSEC_XAUTH_RSA = 4;
public static final int TYPE_IPSEC_HYBRID_RSA = 5;
public static final int TYPE_MAX = 5;
// Entity fields.
public final String key; // -1
public String name = ""; // 0
public int type = TYPE_PPTP; // 1
public String server = ""; // 2
public String username = ""; // 3
public String password = ""; // 4
public String dnsServers = ""; // 5
public String searchDomains = ""; // 6
public String routes = ""; // 7
public boolean mppe = true; // 8
public String l2tpSecret = ""; // 9
public String ipsecIdentifier = "";// 10
public String ipsecSecret = ""; // 11
public String ipsecUserCert = ""; // 12
public String ipsecCaCert = ""; // 13
public String ipsecServerCert = "";// 14
// Helper fields.
public boolean saveLogin = false;
public VpnProfile(String key) {
this.key = key;
}
public VpnProfile(Parcel in) {
key = in.readString();
name = in.readString();
type = in.readInt();
server = in.readString();
username = in.readString();
password = in.readString();
dnsServers = in.readString();
searchDomains = in.readString();
routes = in.readString();
mppe = in.readInt() != 0;
l2tpSecret = in.readString();
ipsecIdentifier = in.readString();
ipsecSecret = in.readString();
ipsecUserCert = in.readString();
ipsecCaCert = in.readString();
ipsecServerCert = in.readString();
saveLogin = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(key);
out.writeString(name);
out.writeInt(type);
out.writeString(server);
out.writeString(username);
out.writeString(password);
out.writeString(dnsServers);
out.writeString(searchDomains);
out.writeString(routes);
out.writeInt(mppe ? 1 : 0);
out.writeString(l2tpSecret);
out.writeString(ipsecIdentifier);
out.writeString(ipsecSecret);
out.writeString(ipsecUserCert);
out.writeString(ipsecCaCert);
out.writeString(ipsecServerCert);
out.writeInt(saveLogin ? 1 : 0);
}
public static VpnProfile decode(String key, byte[] value) {
try {
if (key == null) {
return null;
}
String[] values = new String(value, Charset.forName("UTF-8")).split("\0", -1);
// There can be 14 or 15 values in ICS MR1.
if (values.length < 14 || values.length > 15) {
return null;
}
VpnProfile profile = new VpnProfile(key);
profile.name = values[0];
profile.type = Integer.valueOf(values[1]);
if (profile.type < 0 || profile.type > TYPE_MAX) {
return null;
}
profile.server = values[2];
profile.username = values[3];
profile.password = values[4];
profile.dnsServers = values[5];
profile.searchDomains = values[6];
profile.routes = values[7];
profile.mppe = Boolean.valueOf(values[8]);
profile.l2tpSecret = values[9];
profile.ipsecIdentifier = values[10];
profile.ipsecSecret = values[11];
profile.ipsecUserCert = values[12];
profile.ipsecCaCert = values[13];
profile.ipsecServerCert = (values.length > 14) ? values[14] : "";
profile.saveLogin = !profile.username.isEmpty() || !profile.password.isEmpty();
return profile;
} catch (Exception e) {
// ignore
}
return null;
}
public byte[] encode() {
StringBuilder builder = new StringBuilder(name);
builder.append('\0').append(type);
builder.append('\0').append(server);
builder.append('\0').append(saveLogin ? username : "");
builder.append('\0').append(saveLogin ? password : "");
builder.append('\0').append(dnsServers);
builder.append('\0').append(searchDomains);
builder.append('\0').append(routes);
builder.append('\0').append(mppe);
builder.append('\0').append(l2tpSecret);
builder.append('\0').append(ipsecIdentifier);
builder.append('\0').append(ipsecSecret);
builder.append('\0').append(ipsecUserCert);
builder.append('\0').append(ipsecCaCert);
builder.append('\0').append(ipsecServerCert);
return builder.toString().getBytes(Charset.forName("UTF-8"));
}
/**
* Test if profile is valid for lockdown, which requires IPv4 address for
* both server and DNS. Server hostnames would require using DNS before
* connection.
*/
public boolean isValidLockdownProfile() {
try {
return true;
} catch (IllegalArgumentException e) {
Timber.w("Invalid address", e);
return false;
}
}
public static final Creator<VpnProfile> CREATOR = new Creator<VpnProfile>() {
@Override
public VpnProfile createFromParcel(Parcel in) {
return new VpnProfile(in);
}
@Override
public VpnProfile[] newArray(int size) {
return new VpnProfile[size];
}
};
@Override
public int describeContents() {
return 0;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013 Jacob Klinker * Copyright (C) 2006 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,19 +14,23 @@
* limitations under the License. * limitations under the License.
*/ */
package com.klinker.android.send_message package com.android.internal.telephony;
/** /**
* Class to house all of the settings that can be used to send a message * {@hide}
*/ */
class Settings @JvmOverloads constructor( @SuppressWarnings("serial")
// MMS options public class EncodeException extends Exception {
var mmsc: String? = "", public EncodeException() {
var proxy: String? = "", super();
var port: String? = "0", }
var agent: String? = "",
var userProfileUrl: String? = "", public EncodeException(String s) {
var uaProfTagName: String? = "", super(s);
}
public EncodeException(char c) {
super("Unencodable char: '" + c + "'");
}
}
// SMS options
var stripUnicode: Boolean = false)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,518 @@
/*
* Copyright (C) 2006 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 com.android.internal.telephony;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import java.io.UnsupportedEncodingException;
/**
* Various methods, useful for dealing with SIM data.
*/
public class IccUtils {
static final String LOG_TAG = "IccUtils";
/**
* Many fields in GSM SIM's are stored as nibble-swizzled BCD
* <p/>
* Assumes left-justified field that may be padded right with 0xf
* values.
* <p/>
* Stops on invalid BCD value, returning string so far
*/
public static String
bcdToString(byte[] data, int offset, int length) {
StringBuilder ret = new StringBuilder(length * 2);
for (int i = offset; i < offset + length; i++) {
int v;
v = data[i] & 0xf;
if (v > 9) break;
ret.append((char) ('0' + v));
v = (data[i] >> 4) & 0xf;
// Some PLMNs have 'f' as high nibble, ignore it
if (v == 0xf) continue;
if (v > 9) break;
ret.append((char) ('0' + v));
}
return ret.toString();
}
/**
* Decode cdma byte into String.
*/
public static String
cdmaBcdToString(byte[] data, int offset, int length) {
StringBuilder ret = new StringBuilder(length);
int count = 0;
for (int i = offset; count < length; i++) {
int v;
v = data[i] & 0xf;
if (v > 9) v = 0;
ret.append((char) ('0' + v));
if (++count == length) break;
v = (data[i] >> 4) & 0xf;
if (v > 9) v = 0;
ret.append((char) ('0' + v));
++count;
}
return ret.toString();
}
/**
* Decodes a GSM-style BCD byte, returning an int ranging from 0-99.
* <p/>
* In GSM land, the least significant BCD digit is stored in the most
* significant nibble.
* <p/>
* Out-of-range digits are treated as 0 for the sake of the time stamp,
* because of this:
* <p/>
* TS 23.040 section 9.2.3.11
* "if the MS receives a non-integer value in the SCTS, it shall
* assume the digit is set to 0 but shall store the entire field
* exactly as received"
*/
public static int
gsmBcdByteToInt(byte b) {
int ret = 0;
// treat out-of-range BCD values as 0
if ((b & 0xf0) <= 0x90) {
ret = (b >> 4) & 0xf;
}
if ((b & 0x0f) <= 0x09) {
ret += (b & 0xf) * 10;
}
return ret;
}
/**
* Decodes a CDMA style BCD byte like {@link gsmBcdByteToInt}, but
* opposite nibble format. The least significant BCD digit
* is in the least significant nibble and the most significant
* is in the most significant nibble.
*/
public static int
cdmaBcdByteToInt(byte b) {
int ret = 0;
// treat out-of-range BCD values as 0
if ((b & 0xf0) <= 0x90) {
ret = ((b >> 4) & 0xf) * 10;
}
if ((b & 0x0f) <= 0x09) {
ret += (b & 0xf);
}
return ret;
}
/**
* Decodes a string field that's formatted like the EF[ADN] alpha
* identifier
* <p/>
* From TS 51.011 10.5.1:
* Coding:
* this alpha tagging shall use either
* - the SMS default 7 bit coded alphabet as defined in
* TS 23.038 [12] with bit 8 set to 0. The alpha identifier
* shall be left justified. Unused bytes shall be set to 'FF'; or
* - one of the UCS2 coded options as defined in annex B.
* <p/>
* Annex B from TS 11.11 V8.13.0:
* 1) If the first octet in the alpha string is '80', then the
* remaining octets are 16 bit UCS2 characters ...
* 2) if the first octet in the alpha string is '81', then the
* second octet contains a value indicating the number of
* characters in the string, and the third octet contains an
* 8 bit number which defines bits 15 to 8 of a 16 bit
* base pointer, where bit 16 is set to zero and bits 7 to 1
* are also set to zero. These sixteen bits constitute a
* base pointer to a "half page" in the UCS2 code space, to be
* used with some or all of the remaining octets in the string.
* The fourth and subsequent octets contain codings as follows:
* If bit 8 of the octet is set to zero, the remaining 7 bits
* of the octet contain a GSM Default Alphabet character,
* whereas if bit 8 of the octet is set to one, then the
* remaining seven bits are an offset value added to the
* 16 bit base pointer defined earlier...
* 3) If the first octet of the alpha string is set to '82', then
* the second octet contains a value indicating the number of
* characters in the string, and the third and fourth octets
* contain a 16 bit number which defines the complete 16 bit
* base pointer to a "half page" in the UCS2 code space...
*/
public static String
adnStringFieldToString(byte[] data, int offset, int length) {
if (length == 0) {
return "";
}
if (length >= 1) {
if (data[offset] == (byte) 0x80) {
int ucslen = (length - 1) / 2;
String ret = null;
try {
ret = new String(data, offset + 1, ucslen * 2, "utf-16be");
} catch (UnsupportedEncodingException ex) {
Log.e(LOG_TAG, "implausible UnsupportedEncodingException",
ex);
}
if (ret != null) {
// trim off trailing FFFF characters
ucslen = ret.length();
while (ucslen > 0 && ret.charAt(ucslen - 1) == '\uFFFF')
ucslen--;
return ret.substring(0, ucslen);
}
}
}
boolean isucs2 = false;
char base = '\0';
int len = 0;
if (length >= 3 && data[offset] == (byte) 0x81) {
len = data[offset + 1] & 0xFF;
if (len > length - 3)
len = length - 3;
base = (char) ((data[offset + 2] & 0xFF) << 7);
offset += 3;
isucs2 = true;
} else if (length >= 4 && data[offset] == (byte) 0x82) {
len = data[offset + 1] & 0xFF;
if (len > length - 4)
len = length - 4;
base = (char) (((data[offset + 2] & 0xFF) << 8) |
(data[offset + 3] & 0xFF));
offset += 4;
isucs2 = true;
}
if (isucs2) {
StringBuilder ret = new StringBuilder();
while (len > 0) {
// UCS2 subset case
if (data[offset] < 0) {
ret.append((char) (base + (data[offset] & 0x7F)));
offset++;
len--;
}
// GSM character set case
int count = 0;
while (count < len && data[offset + count] >= 0)
count++;
ret.append(GsmAlphabet.gsm8BitUnpackedToString(data,
offset, count));
offset += count;
len -= count;
}
return ret.toString();
}
Resources resource = Resources.getSystem();
String defaultCharset = "";
return GsmAlphabet.gsm8BitUnpackedToString(data, offset, length, defaultCharset.trim());
}
static int
hexCharToInt(char c) {
if (c >= '0' && c <= '9') return (c - '0');
if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
throw new RuntimeException("invalid hex char '" + c + "'");
}
/**
* Converts a hex String to a byte array.
*
* @param s A string of hexadecimal characters, must be an even number of
* chars long
* @return byte array representation
* @throws RuntimeException on invalid format
*/
public static byte[]
hexStringToBytes(String s) {
byte[] ret;
if (s == null) return null;
int sz = s.length();
ret = new byte[sz / 2];
for (int i = 0; i < sz; i += 2) {
ret[i / 2] = (byte) ((hexCharToInt(s.charAt(i)) << 4)
| hexCharToInt(s.charAt(i + 1)));
}
return ret;
}
/**
* Converts a byte array into a String of hexadecimal characters.
*
* @param bytes an array of bytes
* @return hex string representation of bytes array
*/
public static String
bytesToHexString(byte[] bytes) {
if (bytes == null) return null;
StringBuilder ret = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int b;
b = 0x0f & (bytes[i] >> 4);
ret.append("0123456789abcdef".charAt(b));
b = 0x0f & bytes[i];
ret.append("0123456789abcdef".charAt(b));
}
return ret.toString();
}
/**
* Convert a TS 24.008 Section 10.5.3.5a Network Name field to a string
* "offset" points to "octet 3", the coding scheme byte
* empty string returned on decode error
*/
public static String
networkNameToString(byte[] data, int offset, int length) {
String ret;
if ((data[offset] & 0x80) != 0x80 || length < 1) {
return "";
}
switch ((data[offset] >>> 4) & 0x7) {
case 0:
// SMS character set
int countSeptets;
int unusedBits = data[offset] & 7;
countSeptets = (((length - 1) * 8) - unusedBits) / 7;
ret = GsmAlphabet.gsm7BitPackedToString(data, offset + 1, countSeptets);
break;
case 1:
// UCS2
try {
ret = new String(data,
offset + 1, length - 1, "utf-16");
} catch (UnsupportedEncodingException ex) {
ret = "";
Log.e(LOG_TAG, "implausible UnsupportedEncodingException", ex);
}
break;
// unsupported encoding
default:
ret = "";
break;
}
// "Add CI"
// "The MS should add the letters for the Country's Initials and
// a separator (e.g. a space) to the text string"
if ((data[offset] & 0x40) != 0) {
// FIXME(mkf) add country initials here
}
return ret;
}
/**
* Convert a TS 131.102 image instance of code scheme '11' into Bitmap
*
* @param data The raw data
* @param length The length of image body
* @return The bitmap
*/
public static Bitmap parseToBnW(byte[] data, int length) {
int valueIndex = 0;
int width = data[valueIndex++] & 0xFF;
int height = data[valueIndex++] & 0xFF;
int numOfPixels = width * height;
int[] pixels = new int[numOfPixels];
int pixelIndex = 0;
int bitIndex = 7;
byte currentByte = 0x00;
while (pixelIndex < numOfPixels) {
// reassign data and index for every byte (8 bits).
if (pixelIndex % 8 == 0) {
currentByte = data[valueIndex++];
bitIndex = 7;
}
pixels[pixelIndex++] = bitToRGB((currentByte >> bitIndex--) & 0x01);
}
;
if (pixelIndex != numOfPixels) {
Log.e(LOG_TAG, "parse end and size error");
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
}
private static int bitToRGB(int bit) {
if (bit == 1) {
return Color.WHITE;
} else {
return Color.BLACK;
}
}
/**
* a TS 131.102 image instance of code scheme '11' into color Bitmap
*
* @param data The raw data
* @param length the length of image body
* @param transparency with or without transparency
* @return The color bitmap
*/
public static Bitmap parseToRGB(byte[] data, int length,
boolean transparency) {
int valueIndex = 0;
int width = data[valueIndex++] & 0xFF;
int height = data[valueIndex++] & 0xFF;
int bits = data[valueIndex++] & 0xFF;
int colorNumber = data[valueIndex++] & 0xFF;
int clutOffset = ((data[valueIndex++] & 0xFF) << 8)
| (data[valueIndex++] & 0xFF);
int[] colorIndexArray = getCLUT(data, clutOffset, colorNumber);
if (true == transparency) {
colorIndexArray[colorNumber - 1] = Color.TRANSPARENT;
}
int[] resultArray = null;
if (0 == (8 % bits)) {
resultArray = mapTo2OrderBitColor(data, valueIndex,
(width * height), colorIndexArray, bits);
} else {
resultArray = mapToNon2OrderBitColor(data, valueIndex,
(width * height), colorIndexArray, bits);
}
return Bitmap.createBitmap(resultArray, width, height,
Bitmap.Config.RGB_565);
}
private static int[] mapTo2OrderBitColor(byte[] data, int valueIndex,
int length, int[] colorArray, int bits) {
if (0 != (8 % bits)) {
Log.e(LOG_TAG, "not event number of color");
return mapToNon2OrderBitColor(data, valueIndex, length, colorArray,
bits);
}
int mask = 0x01;
switch (bits) {
case 1:
mask = 0x01;
break;
case 2:
mask = 0x03;
break;
case 4:
mask = 0x0F;
break;
case 8:
mask = 0xFF;
break;
}
int[] resultArray = new int[length];
int resultIndex = 0;
int run = 8 / bits;
while (resultIndex < length) {
byte tempByte = data[valueIndex++];
for (int runIndex = 0; runIndex < run; ++runIndex) {
int offset = run - runIndex - 1;
resultArray[resultIndex++] = colorArray[(tempByte >> (offset * bits))
& mask];
}
}
return resultArray;
}
private static int[] mapToNon2OrderBitColor(byte[] data, int valueIndex,
int length, int[] colorArray, int bits) {
if (0 == (8 % bits)) {
Log.e(LOG_TAG, "not odd number of color");
return mapTo2OrderBitColor(data, valueIndex, length, colorArray,
bits);
}
int[] resultArray = new int[length];
// TODO fix me:
return resultArray;
}
private static int[] getCLUT(byte[] rawData, int offset, int number) {
if (null == rawData) {
return null;
}
int[] result = new int[number];
int endIndex = offset + (number * 3); // 1 color use 3 bytes
int valueIndex = offset;
int colorIndex = 0;
int alpha = 0xff << 24;
do {
result[colorIndex++] = alpha
| ((rawData[valueIndex++] & 0xFF) << 16)
| ((rawData[valueIndex++] & 0xFF) << 8)
| ((rawData[valueIndex++] & 0xFF));
} while (valueIndex < endIndex);
return result;
}
}
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2012 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 com.android.internal.telephony;
/**
* SMS Constants and must be the same as the corresponding
* deprecated version in SmsMessage.
*
* @hide
*/
public class SmsConstants {
/**
* User data text encoding code unit size
*/
public static final int ENCODING_UNKNOWN = 0;
public static final int ENCODING_7BIT = 1;
public static final int ENCODING_8BIT = 2;
public static final int ENCODING_16BIT = 3;
/**
* The maximum number of payload septets per message
*/
public static final int MAX_USER_DATA_SEPTETS = 160;
/**
* The maximum number of payload septets per message if a user data header
* is present. This assumes the header only contains the
* CONCATENATED_8_BIT_REFERENCE element.
*/
public static final int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153;
/**
* This value is not defined in global standard. Only in Korea, this is used.
*/
public static final int ENCODING_KSC5601 = 4;
/**
* The maximum number of payload bytes per message
*/
public static final int MAX_USER_DATA_BYTES = 140;
/**
* The maximum number of payload bytes per message if a user data header
* is present. This assumes the header only contains the
* CONCATENATED_8_BIT_REFERENCE element.
*/
public static final int MAX_USER_DATA_BYTES_WITH_HEADER = 134;
/**
* SMS Class enumeration.
* See TS 23.038.
*/
public enum MessageClass {
UNKNOWN, CLASS_0, CLASS_1, CLASS_2, CLASS_3;
}
/**
* Indicates a 3GPP format SMS message.
*
* @hide pending API council approval
*/
public static final String FORMAT_3GPP = "3gpp";
/**
* Indicates a 3GPP2 format SMS message.
*
* @hide pending API council approval
*/
public static final String FORMAT_3GPP2 = "3gpp2";
}
@@ -0,0 +1,243 @@
/*
* Copyright (C) 2006 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 com.android.internal.util;
import java.lang.reflect.Array;
// XXX these should be changed to reflect the actual memory allocator we use.
// it looks like right now objects want to be powers of 2 minus 8
// and the array size eats another 4 bytes
/**
* ArrayUtils contains some methods that you can call to find out
* the most efficient increments by which to grow arrays.
*/
public class ArrayUtils {
private static Object[] EMPTY = new Object[0];
private static final int CACHE_SIZE = 73;
private static Object[] sCache = new Object[CACHE_SIZE];
private ArrayUtils() { /* cannot be instantiated */ }
public static int idealByteArraySize(int need) {
for (int i = 4; i < 32; i++)
if (need <= (1 << i) - 12)
return (1 << i) - 12;
return need;
}
public static int idealBooleanArraySize(int need) {
return idealByteArraySize(need);
}
public static int idealShortArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealCharArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealIntArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealFloatArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealObjectArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealLongArraySize(int need) {
return idealByteArraySize(need * 8) / 8;
}
/**
* Checks if the beginnings of two byte arrays are equal.
*
* @param array1 the first byte array
* @param array2 the second byte array
* @param length the number of bytes to check
* @return true if they're equal, false otherwise
*/
public static boolean equals(byte[] array1, byte[] array2, int length) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length < length || array2.length < length) {
return false;
}
for (int i = 0; i < length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Returns an empty array of the specified type. The intent is that
* it will return the same empty array every time to avoid reallocation,
* although this is not guaranteed.
*/
@SuppressWarnings("unchecked")
public static <T> T[] emptyArray(Class<T> kind) {
if (kind == Object.class) {
return (T[]) EMPTY;
}
int bucket = ((System.identityHashCode(kind) / 8) & 0x7FFFFFFF) % CACHE_SIZE;
Object cache = sCache[bucket];
if (cache == null || cache.getClass().getComponentType() != kind) {
cache = Array.newInstance(kind, 0);
sCache[bucket] = cache;
// Log.e("cache", "new empty " + kind.getName() + " at " + bucket);
}
return (T[]) cache;
}
/**
* Checks that value is present as at least one of the elements of the array.
*
* @param array the array to check in
* @param value the value to check for
* @return true if the value is present in the array
*/
public static <T> boolean contains(T[] array, T value) {
for (T element : array) {
if (element == null) {
if (value == null) return true;
} else {
if (value != null && element.equals(value)) return true;
}
}
return false;
}
public static boolean contains(int[] array, int value) {
for (int element : array) {
if (element == value) {
return true;
}
}
return false;
}
public static long total(long[] array) {
long total = 0;
for (long value : array) {
total += value;
}
return total;
}
/**
* Appends an element to a copy of the array and returns the copy.
*
* @param array The original array, or null to represent an empty array.
* @param element The element to add.
* @return A new array that contains all of the elements of the original array
* with the specified element added at the end.
*/
@SuppressWarnings("unchecked")
public static <T> T[] appendElement(Class<T> kind, T[] array, T element) {
final T[] result;
final int end;
if (array != null) {
end = array.length;
result = (T[]) Array.newInstance(kind, end + 1);
System.arraycopy(array, 0, result, 0, end);
} else {
end = 0;
result = (T[]) Array.newInstance(kind, 1);
}
result[end] = element;
return result;
}
/**
* Removes an element from a copy of the array and returns the copy.
* If the element is not present, then the original array is returned unmodified.
*
* @param array The original array, or null to represent an empty array.
* @param element The element to remove.
* @return A new array that contains all of the elements of the original array
* except the first copy of the specified element removed. If the specified element
* was not present, then returns the original array. Returns null if the result
* would be an empty array.
*/
@SuppressWarnings("unchecked")
public static <T> T[] removeElement(Class<T> kind, T[] array, T element) {
if (array != null) {
final int length = array.length;
for (int i = 0; i < length; i++) {
if (array[i] == element) {
if (length == 1) {
return null;
}
T[] result = (T[]) Array.newInstance(kind, length - 1);
System.arraycopy(array, 0, result, 0, i);
System.arraycopy(array, i + 1, result, i, length - i - 1);
return result;
}
}
}
return array;
}
public static int[] appendInt(int[] cur, int val) {
if (cur == null) {
return new int[]{val};
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
return cur;
}
}
int[] ret = new int[N + 1];
System.arraycopy(cur, 0, ret, 0, N);
ret[N] = val;
return ret;
}
public static int[] removeInt(int[] cur, int val) {
if (cur == null) {
return null;
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
int[] ret = new int[N - 1];
if (i > 0) {
System.arraycopy(cur, 0, ret, 0, i);
}
if (i < (N - 1)) {
System.arraycopy(cur, i + 1, ret, i, N - i - 1);
}
return ret;
}
}
return cur;
}
}
@@ -0,0 +1,62 @@
/*
* Copyright (C) 2007 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 com.android.internal.util;
import java.util.Arrays;
/**
* Object utility methods.
*/
public class Objects {
/**
* Determines whether two possibly-null objects are equal. Returns:
* <p/>
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are
* equal according to {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
* <p/>
* <p>This assumes that any non-null objects passed to this function conform
* to the {@code equals()} contract.
*/
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Generates a hash code for multiple values. The hash code is generated by
* calling {@link Arrays#hashCode(Object[])}.
* <p/>
* <p>This is useful for implementing {@link Object#hashCode()}. For example,
* in an object that has three properties, {@code x}, {@code y}, and
* {@code z}, one could write:
* <pre>
* public int hashCode() {
* return Objects.hashCode(getX(), getY(), getZ());
* }</pre>
*
* <b>Warning</b>: When a single object is supplied, the returned hash code
* does not equal the hash code of that object.
*/
public static int hashCode(Object... objects) {
return Arrays.hashCode(objects);
}
}
@@ -0,0 +1,69 @@
/*
* 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 com.android.internal.util;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state.
*/
public class Preconditions {
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
}
+14 -8
View File
@@ -16,22 +16,28 @@
package com.android.mms; package com.android.mms;
import android.content.Context; import java.io.IOException;
import android.content.res.XmlResourceParser;
import com.klinker.android.send_message.R; import com.klinker.android.send_message.R;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import timber.log.Timber; import timber.log.Timber;
import java.io.IOException;
public class MmsConfig { public class MmsConfig {
private static final String TAG = "MmsConfig";
private static final boolean DEBUG = true; private static final boolean DEBUG = true;
private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGV = true;
public static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile"; public static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile";
public static final String DEFAULT_USER_AGENT = "Android-Mms/2.0"; public static final String DEFAULT_USER_AGENT = "Android-Mms/2.0";
private static final String MMS_APP_PACKAGE = "com.android.mms";
private static final String SMS_PROMO_DISMISSED_KEY = "sms_promo_dismissed_key";
private static final int MAX_IMAGE_HEIGHT = 480; private static final int MAX_IMAGE_HEIGHT = 480;
private static final int MAX_IMAGE_WIDTH = 640; private static final int MAX_IMAGE_WIDTH = 640;
private static final int MAX_TEXT_LENGTH = 2000; private static final int MAX_TEXT_LENGTH = 2000;
@@ -296,11 +302,11 @@ public class MmsConfig {
} }
} }
} catch (XmlPullParserException e) { } catch (XmlPullParserException e) {
Timber.e(e, "loadMmsSettings caught "); Timber.e("loadMmsSettings caught ", e);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Timber.e(e, "loadMmsSettings caught "); Timber.e("loadMmsSettings caught ", e);
} catch (IOException e) { } catch (IOException e) {
Timber.e(e, "loadMmsSettings caught "); Timber.e("loadMmsSettings caught ", e);
} finally { } finally {
parser.close(); parser.close();
} }
View File
View File
View File
+2 -2
View File
@@ -17,12 +17,12 @@
package com.android.mms.dom; package com.android.mms.dom;
import java.util.Vector;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import java.util.Vector;
public class NamedNodeMapImpl implements NamedNodeMap { public class NamedNodeMapImpl implements NamedNodeMap {
private Vector<Node> mNodes = new Vector<Node>(); private Vector<Node> mNodes = new Vector<Node>();
+4 -3
View File
@@ -17,7 +17,9 @@
package com.android.mms.dom; package com.android.mms.dom;
import com.android.mms.dom.events.EventTargetImpl; import java.util.NoSuchElementException;
import java.util.Vector;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
@@ -29,8 +31,7 @@ import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget; import org.w3c.dom.events.EventTarget;
import java.util.NoSuchElementException; import com.android.mms.dom.events.EventTargetImpl;
import java.util.Vector;
public abstract class NodeImpl implements Node, EventTarget { public abstract class NodeImpl implements Node, EventTarget {
private Node mParentNode; private Node mParentNode;
+2 -2
View File
@@ -17,11 +17,11 @@
package com.android.mms.dom; package com.android.mms.dom;
import java.util.ArrayList;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import java.util.ArrayList;
public class NodeListImpl implements NodeList { public class NodeListImpl implements NodeList {
private ArrayList<Node> mSearchNodes; private ArrayList<Node> mSearchNodes;
private ArrayList<Node> mStaticNodes; private ArrayList<Node> mStaticNodes;
View File
+7 -3
View File
@@ -16,15 +16,19 @@
package com.android.mms.dom.events; package com.android.mms.dom.events;
import com.android.mms.logs.LogTag;
import java.util.ArrayList;
import org.w3c.dom.events.Event; import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventException; import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget; import org.w3c.dom.events.EventTarget;
import timber.log.Timber; import timber.log.Timber;
import java.util.ArrayList;
public class EventTargetImpl implements EventTarget { public class EventTargetImpl implements EventTarget {
private static final String TAG = LogTag.TAG;
private ArrayList<EventListenerEntry> mListenerEntries; private ArrayList<EventListenerEntry> mListenerEntries;
private EventTarget mNodeTarget; private EventTarget mNodeTarget;
@@ -96,7 +100,7 @@ public class EventTargetImpl implements EventTarget {
catch (Exception e) { catch (Exception e) {
// Any exceptions thrown inside an EventListener will // Any exceptions thrown inside an EventListener will
// not stop propagation of the event // not stop propagation of the event
Timber.w(e, "Catched EventListener exception"); Timber.w("Catched EventListener exception", e);
} }
} }
} }
@@ -17,7 +17,8 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.dom.NodeListImpl; import java.util.ArrayList;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
@@ -27,7 +28,7 @@ import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time; import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList; import org.w3c.dom.smil.TimeList;
import java.util.ArrayList; import com.android.mms.dom.NodeListImpl;
public abstract class ElementParallelTimeContainerImpl extends ElementTimeContainerImpl public abstract class ElementParallelTimeContainerImpl extends ElementTimeContainerImpl
implements ElementParallelTimeContainer { implements ElementParallelTimeContainer {
@@ -17,14 +17,15 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.dom.NodeListImpl; import java.util.ArrayList;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementSequentialTimeContainer; import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement; import org.w3c.dom.smil.SMILElement;
import java.util.ArrayList; import com.android.mms.dom.NodeListImpl;
public abstract class ElementSequentialTimeContainerImpl extends public abstract class ElementSequentialTimeContainerImpl extends
ElementTimeContainerImpl implements ElementSequentialTimeContainer { ElementTimeContainerImpl implements ElementSequentialTimeContainer {
+7 -3
View File
@@ -16,16 +16,20 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.logs.LogTag;
import java.util.ArrayList;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement; import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time; import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList; import org.w3c.dom.smil.TimeList;
import timber.log.Timber; import timber.log.Timber;
import java.util.ArrayList;
public abstract class ElementTimeImpl implements ElementTime { public abstract class ElementTimeImpl implements ElementTime {
private static final String TAG = LogTag.TAG;
private static final String FILL_REMOVE_ATTRIBUTE = "remove"; private static final String FILL_REMOVE_ATTRIBUTE = "remove";
private static final String FILL_FREEZE_ATTRIBUTE = "freeze"; private static final String FILL_FREEZE_ATTRIBUTE = "freeze";
@@ -129,7 +133,7 @@ public abstract class ElementTimeImpl implements ElementTime {
getEndConstraints())); getEndConstraints()));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// Ignore badly formatted times // Ignore badly formatted times
Timber.e(e, "Malformed time value."); Timber.e("Malformed time value.", e);
} }
} }
} }
+3 -2
View File
@@ -16,8 +16,6 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.dom.DocumentImpl;
import com.android.mms.dom.events.EventImpl;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
@@ -31,6 +29,9 @@ import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.SMILLayoutElement; import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.TimeList; import org.w3c.dom.smil.TimeList;
import com.android.mms.dom.DocumentImpl;
import com.android.mms.dom.events.EventImpl;
public class SmilDocumentImpl extends DocumentImpl implements SMILDocument, DocumentEvent { public class SmilDocumentImpl extends DocumentImpl implements SMILDocument, DocumentEvent {
/* /*
* The sequential time container cannot be initialized here because the real container * The sequential time container cannot be initialized here because the real container
+2 -1
View File
@@ -17,10 +17,11 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.dom.ElementImpl;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILElement; import org.w3c.dom.smil.SMILElement;
import com.android.mms.dom.ElementImpl;
public class SmilElementImpl extends ElementImpl implements SMILElement { public class SmilElementImpl extends ElementImpl implements SMILElement {
/** /**
* This constructor is used by the factory methods of the SmilDocument. * This constructor is used by the factory methods of the SmilDocument.
@@ -17,11 +17,12 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.layout.LayoutManager;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILLayoutElement; import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.SMILRootLayoutElement; import org.w3c.dom.smil.SMILRootLayoutElement;
import com.android.mms.layout.LayoutManager;
public class SmilLayoutElementImpl extends SmilElementImpl implements public class SmilLayoutElementImpl extends SmilElementImpl implements
SMILLayoutElement { SMILLayoutElement {
SmilLayoutElementImpl(SmilDocumentImpl owner, String tagName) { SmilLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
+8 -2
View File
@@ -16,20 +16,26 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.dom.events.EventImpl;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.events.DocumentEvent; import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event; import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILMediaElement; import org.w3c.dom.smil.SMILMediaElement;
import org.w3c.dom.smil.TimeList; import org.w3c.dom.smil.TimeList;
import timber.log.Timber; import timber.log.Timber;
public class SmilMediaElementImpl extends SmilElementImpl implements SMILMediaElement { import com.android.mms.logs.LogTag;
import com.android.mms.dom.events.EventImpl;
public class SmilMediaElementImpl extends SmilElementImpl implements
SMILMediaElement {
public final static String SMIL_MEDIA_START_EVENT = "SmilMediaStart"; public final static String SMIL_MEDIA_START_EVENT = "SmilMediaStart";
public final static String SMIL_MEDIA_END_EVENT = "SmilMediaEnd"; public final static String SMIL_MEDIA_END_EVENT = "SmilMediaEnd";
public final static String SMIL_MEDIA_PAUSE_EVENT = "SmilMediaPause"; public final static String SMIL_MEDIA_PAUSE_EVENT = "SmilMediaPause";
public final static String SMIL_MEDIA_SEEK_EVENT = "SmilMediaSeek"; public final static String SMIL_MEDIA_SEEK_EVENT = "SmilMediaSeek";
private final static String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGV = false;
ElementTime mElementTime = new ElementTimeImpl(this) { ElementTime mElementTime = new ElementTimeImpl(this) {
+2 -2
View File
@@ -17,6 +17,8 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent; import org.w3c.dom.events.DocumentEvent;
@@ -27,8 +29,6 @@ import org.w3c.dom.smil.SMILParElement;
import org.w3c.dom.smil.Time; import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList; import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class SmilParElementImpl extends SmilElementImpl implements SMILParElement { public class SmilParElementImpl extends SmilElementImpl implements SMILParElement {
public final static String SMIL_SLIDE_START_EVENT = "SmilSlideStart"; public final static String SMIL_SLIDE_START_EVENT = "SmilSlideStart";
public final static String SMIL_SLIDE_END_EVENT = "SmilSlideEnd"; public final static String SMIL_SLIDE_END_EVENT = "SmilSlideEnd";
@@ -0,0 +1,762 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.dom.smil;
import com.android.mms.logs.LogTag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import timber.log.Timber;
/**
* The SmilPlayer is responsible for playing, stopping, pausing and resuming a SMIL tree.
* <li>It creates a whole timeline before playing.</li>
* <li>The player runs in a different thread which intends not to block the main thread.</li>
*/
public class SmilPlayer implements Runnable {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private static final int TIMESLICE = 200;
private static enum SmilPlayerState {
INITIALIZED,
PLAYING,
PLAYED,
PAUSED,
STOPPED,
}
private static enum SmilPlayerAction {
NO_ACTIVE_ACTION,
RELOAD,
STOP,
PAUSE,
START,
NEXT,
PREV
}
public static final String MEDIA_TIME_UPDATED_EVENT = "mediaTimeUpdated";
private static final Comparator<TimelineEntry> sTimelineEntryComparator =
new Comparator<TimelineEntry>() {
public int compare(TimelineEntry o1, TimelineEntry o2) {
return Double.compare(o1.getOffsetTime(), o2.getOffsetTime());
}
};
private static SmilPlayer sPlayer;
private long mCurrentTime;
private int mCurrentElement;
private int mCurrentSlide;
private ArrayList<TimelineEntry> mAllEntries;
private ElementTime mRoot;
private Thread mPlayerThread;
private SmilPlayerState mState = SmilPlayerState.INITIALIZED;
private SmilPlayerAction mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
private ArrayList<ElementTime> mActiveElements;
private Event mMediaTimeUpdatedEvent;
private static ArrayList<TimelineEntry> getParTimeline(
ElementParallelTimeContainer par, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
// Set my begin at first
TimeList myBeginList = par.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, par, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = par.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, par, TimelineEntry.ACTION_END);
maxOffset = endOffset;
NodeList children = par.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
}
Collections.sort(timeline, sTimelineEntryComparator);
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = par.getActiveChildrenAt(
(float) (endOffset - offset) * 1000);
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getSeqTimeline(
ElementSequentialTimeContainer seq, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
double orgOffset = offset;
// Set my begin at first
TimeList myBeginList = seq.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, seq, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = seq.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, seq, TimelineEntry.ACTION_END);
maxOffset = endOffset;
// Get children's timelines
NodeList children = seq.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
// Since the child timeline has been sorted, the offset of the last one is the biggest.
offset = childTimeline.get(childTimeline.size() - 1).getOffsetTime();
}
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = seq.getActiveChildrenAt(
(float) (endOffset - orgOffset));
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getTimeline(ElementTime element,
double offset, double maxOffset) {
if (element instanceof ElementParallelTimeContainer) {
return getParTimeline((ElementParallelTimeContainer) element, offset, maxOffset);
} else if (element instanceof ElementSequentialTimeContainer) {
return getSeqTimeline((ElementSequentialTimeContainer) element, offset, maxOffset);
} else {
// Not ElementTimeContainer here
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
TimeList beginList = element.getBegin();
for (int i = 0; i < beginList.getLength(); ++i) {
Time begin = beginList.item(i);
if (begin.getResolved()) {
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(beginOffset,
element, TimelineEntry.ACTION_BEGIN);
timeline.add(entry);
}
}
}
TimeList endList = element.getEnd();
for (int i = 0; i < endList.getLength(); ++i) {
Time end = endList.item(i);
if (end.getResolved()) {
double endOffset = end.getResolvedOffset() + offset;
if (endOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(endOffset,
element, TimelineEntry.ACTION_END);
timeline.add(entry);
}
}
}
Collections.sort(timeline, sTimelineEntryComparator);
return timeline;
}
}
private SmilPlayer() {
// Private constructor
}
public static SmilPlayer getPlayer() {
if (sPlayer == null) {
sPlayer = new SmilPlayer();
}
return sPlayer;
}
public synchronized boolean isPlayingState() {
return mState == SmilPlayerState.PLAYING;
}
public synchronized boolean isPlayedState() {
return mState == SmilPlayerState.PLAYED;
}
public synchronized boolean isPausedState() {
return mState == SmilPlayerState.PAUSED;
}
public synchronized boolean isStoppedState() {
return mState == SmilPlayerState.STOPPED;
}
private synchronized boolean isPauseAction() {
return mAction == SmilPlayerAction.PAUSE;
}
private synchronized boolean isStartAction() {
return mAction == SmilPlayerAction.START;
}
private synchronized boolean isStopAction() {
return mAction == SmilPlayerAction.STOP;
}
private synchronized boolean isReloadAction() {
return mAction == SmilPlayerAction.RELOAD;
}
private synchronized boolean isNextAction() {
return mAction == SmilPlayerAction.NEXT;
}
private synchronized boolean isPrevAction() {
return mAction == SmilPlayerAction.PREV;
}
public synchronized void init(ElementTime root) {
mRoot = root;
mAllEntries = getTimeline(mRoot, 0, Long.MAX_VALUE);
mMediaTimeUpdatedEvent = ((DocumentEvent) mRoot).createEvent("Event");
mMediaTimeUpdatedEvent.initEvent(MEDIA_TIME_UPDATED_EVENT, false, false);
mActiveElements = new ArrayList<ElementTime>();
}
public synchronized void play() {
if (!isPlayingState()) {
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mPlayerThread = new Thread(this, "SmilPlayer thread");
mState = SmilPlayerState.PLAYING;
mPlayerThread.start();
} else {
Timber.w("Error State: Playback is playing!");
}
}
public synchronized void pause() {
if (isPlayingState()) {
mAction = SmilPlayerAction.PAUSE;
notifyAll();
} else {
Timber.w("Error State: Playback is not playing!");
}
}
public synchronized void start() {
if (isPausedState()) {
resumeActiveElements();
mAction = SmilPlayerAction.START;
notifyAll();
} else if (isPlayedState()) {
play();
} else {
Timber.w("Error State: Playback can not be started!");
}
}
public synchronized void stop() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.STOP;
notifyAll();
} else if (isPlayedState()) {
actionStop();
}
}
public synchronized void stopWhenReload() {
endActiveElements();
}
public synchronized void reload() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.RELOAD;
notifyAll();
} else if (isPlayedState()) {
actionReload();
}
}
public synchronized void next() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.NEXT;
notifyAll();
}
}
public synchronized void prev() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.PREV;
notifyAll();
}
}
private synchronized boolean isBeginOfSlide(TimelineEntry entry) {
return (TimelineEntry.ACTION_BEGIN == entry.getAction())
&& (entry.getElement() instanceof SmilParElementImpl);
}
private synchronized void reloadActiveSlide() {
mActiveElements.clear();
beginSmilDocument();
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
actionEntry(entry);
}
seekActiveMedia();
}
private synchronized void beginSmilDocument() {
TimelineEntry entry = mAllEntries.get(0);
actionEntry(entry);
}
private synchronized double getOffsetTime(ElementTime element) {
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
if (element.equals(entry.getElement())) {
return entry.getOffsetTime() * 1000; // in ms
}
}
return -1;
}
private synchronized void seekActiveMedia() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (element instanceof SmilParElementImpl) {
return;
}
double offset = getOffsetTime(element);
if ((offset >= 0) && (offset <= mCurrentTime)) {
if (LOCAL_LOGV) {
Timber.v("[SEEK] " + " at " + mCurrentTime
+ " " + element);
}
element.seekElement( (float) (mCurrentTime - offset) );
}
}
}
private synchronized void waitForEntry(long interval)
throws InterruptedException {
if (LOCAL_LOGV) {
Timber.v("Waiting for " + interval + "ms.");
}
long overhead = 0;
while (interval > 0) {
long startAt = System.currentTimeMillis();
long sleep = Math.min(interval, TIMESLICE);
if (overhead < sleep) {
wait(sleep - overhead);
mCurrentTime += sleep;
} else {
sleep = 0;
mCurrentTime += overhead;
}
if (isStopAction() || isReloadAction() || isPauseAction() || isNextAction() ||
isPrevAction()) {
return;
}
((EventTarget) mRoot).dispatchEvent(mMediaTimeUpdatedEvent);
interval -= TIMESLICE;
overhead = System.currentTimeMillis() - startAt - sleep;
}
}
public synchronized int getDuration() {
if ((mAllEntries != null) && !mAllEntries.isEmpty()) {
return (int) mAllEntries.get(mAllEntries.size() - 1).mOffsetTime * 1000;
}
return 0;
}
public synchronized int getCurrentPosition() {
return (int) mCurrentTime;
}
private synchronized void endActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Timber.v("[STOP] " + " at " + mCurrentTime
+ " " + element);
}
element.endElement();
}
}
private synchronized void pauseActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Timber.v("[PAUSE] " + " at " + mCurrentTime
+ " " + element);
}
element.pauseElement();
}
}
private synchronized void resumeActiveElements() {
int size = mActiveElements.size();
for (int i = 0; i < size; i++) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Timber.v("[RESUME] " + " at " + mCurrentTime
+ " " + element);
}
element.resumeElement();
}
}
private synchronized void waitForWakeUp() {
try {
while ( !(isStartAction() || isStopAction() || isReloadAction() ||
isNextAction() || isPrevAction()) ) {
wait(TIMESLICE);
}
if (isStartAction()) {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
mState = SmilPlayerState.PLAYING;
}
} catch (InterruptedException e) {
Timber.e("Unexpected InterruptedException.", e);
}
}
private synchronized void actionEntry(TimelineEntry entry) {
switch (entry.getAction()) {
case TimelineEntry.ACTION_BEGIN:
if (LOCAL_LOGV) {
Timber.v("[START] " + " at " + mCurrentTime + " "
+ entry.getElement());
}
entry.getElement().beginElement();
mActiveElements.add(entry.getElement());
break;
case TimelineEntry.ACTION_END:
if (LOCAL_LOGV) {
Timber.v("[STOP] " + " at " + mCurrentTime + " "
+ entry.getElement());
}
entry.getElement().endElement();
mActiveElements.remove(entry.getElement());
break;
default:
break;
}
}
private synchronized TimelineEntry reloadCurrentEntry() {
// Check if the position is less than size of all entries
if (mCurrentElement < mAllEntries.size()) {
return mAllEntries.get(mCurrentElement);
} else {
return null;
}
}
private void stopCurrentSlide() {
HashSet<TimelineEntry> skippedEntries = new HashSet<TimelineEntry>();
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
// Stop any started entries, and skip the not started entries until
// meeting the end of slide
TimelineEntry entry = mAllEntries.get(i);
int action = entry.getAction();
if (entry.getElement() instanceof SmilParElementImpl &&
action == TimelineEntry.ACTION_END) {
actionEntry(entry);
mCurrentElement = i;
break;
} else if (action == TimelineEntry.ACTION_END && !skippedEntries.contains(entry)) {
actionEntry(entry);
} else if (action == TimelineEntry.ACTION_BEGIN) {
skippedEntries.add(entry);
}
}
}
private TimelineEntry loadNextSlide() {
TimelineEntry entry;
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
// No slide, finish play back
mCurrentElement++;
entry = null;
if (mCurrentElement < totalEntries) {
entry = mAllEntries.get(mCurrentElement);
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
}
return entry;
}
private TimelineEntry loadPrevSlide() {
int skippedSlides = 1;
int latestBeginEntryIndex = -1;
for (int i = mCurrentSlide; i >= 0; i--) {
TimelineEntry entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
latestBeginEntryIndex = i;
if (0 == skippedSlides-- ) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
}
if (latestBeginEntryIndex != -1) {
mCurrentElement = latestBeginEntryIndex;
mCurrentSlide = latestBeginEntryIndex;
return mAllEntries.get(mCurrentElement);
}
return null;
}
private synchronized TimelineEntry actionNext() {
stopCurrentSlide();
return loadNextSlide();
}
private synchronized TimelineEntry actionPrev() {
stopCurrentSlide();
return loadPrevSlide();
}
private synchronized void actionPause() {
pauseActiveElements();
mState = SmilPlayerState.PAUSED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionStop() {
endActiveElements();
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mState = SmilPlayerState.STOPPED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionReload() {
reloadActiveSlide();
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
public void run() {
if (isStoppedState()) {
return;
}
if (LOCAL_LOGV) {
dumpAllEntries();
}
// Play the Element by following the timeline
int size = mAllEntries.size();
for (mCurrentElement = 0; mCurrentElement < size; mCurrentElement++) {
TimelineEntry entry = mAllEntries.get(mCurrentElement);
if (isBeginOfSlide(entry)) {
mCurrentSlide = mCurrentElement;
}
long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
while (offset > mCurrentTime) {
try {
waitForEntry(offset - mCurrentTime);
} catch (InterruptedException e) {
Timber.e("Unexpected InterruptedException.", e);
}
while (isPauseAction() || isStopAction() || isReloadAction() || isNextAction() ||
isPrevAction()) {
if (isPauseAction()) {
actionPause();
waitForWakeUp();
}
if (isStopAction()) {
actionStop();
return;
}
if (isReloadAction()) {
actionReload();
entry = reloadCurrentEntry();
if (entry == null)
return;
if (isPausedState()) {
mAction = SmilPlayerAction.PAUSE;
}
}
if (isNextAction()) {
TimelineEntry nextEntry = actionNext();
if (nextEntry != null) {
entry = nextEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
if (isPrevAction()) {
TimelineEntry prevEntry = actionPrev();
if (prevEntry != null) {
entry = prevEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
}
}
mCurrentTime = offset;
actionEntry(entry);
}
mState = SmilPlayerState.PLAYED;
}
private static final class TimelineEntry {
final static int ACTION_BEGIN = 0;
final static int ACTION_END = 1;
private final double mOffsetTime;
private final ElementTime mElement;
private final int mAction;
public TimelineEntry(double offsetTime, ElementTime element, int action) {
mOffsetTime = offsetTime;
mElement = element;
mAction = action;
}
public double getOffsetTime() {
return mOffsetTime;
}
public ElementTime getElement() {
return mElement;
}
public int getAction() {
return mAction;
}
public String toString() {
return "Type = " + mElement + " offset = " + getOffsetTime() + " action = " + getAction();
}
}
private void dumpAllEntries() {
if (LOCAL_LOGV) {
for (TimelineEntry entry : mAllEntries) {
Timber.v("[Entry] "+ entry);
}
}
}
}
@@ -16,9 +16,12 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import com.android.mms.logs.LogTag;
import org.w3c.dom.DOMException; import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILDocument; import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement; import org.w3c.dom.smil.SMILRegionElement;
import timber.log.Timber; import timber.log.Timber;
public class SmilRegionElementImpl extends SmilElementImpl implements public class SmilRegionElementImpl extends SmilElementImpl implements
@@ -44,6 +47,8 @@ public class SmilRegionElementImpl extends SmilElementImpl implements
private static final String RIGHT_ATTRIBUTE_NAME = "right"; private static final String RIGHT_ATTRIBUTE_NAME = "right";
private static final String BOTTOM_ATTRIBUTE_NAME = "bottom"; private static final String BOTTOM_ATTRIBUTE_NAME = "bottom";
private static final String FIT_ATTRIBUTE_NAME = "fit"; private static final String FIT_ATTRIBUTE_NAME = "fit";
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGV = false;
SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) { SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) {
View File
+2 -2
View File
@@ -17,11 +17,11 @@
package com.android.mms.dom.smil; package com.android.mms.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.smil.Time; import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList; import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class TimeListImpl implements TimeList { public class TimeListImpl implements TimeList {
private final ArrayList<Time> mTimes; private final ArrayList<Time> mTimes;
@@ -0,0 +1,94 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.dom.smil.parser;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.smil.SMILDocument;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import timber.log.Timber;
import com.android.mms.logs.LogTag;
import com.android.mms.dom.smil.SmilDocumentImpl;
public class SmilContentHandler extends DefaultHandler {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private SMILDocument mSmilDocument;
private Node mCurrentNode;
/**
* Resets this handler.
*
*/
public void reset() {
mSmilDocument = new SmilDocumentImpl();
mCurrentNode = mSmilDocument;
}
/**
* Returns the SMILDocument.
* @return The SMILDocument instance
*/
public SMILDocument getSmilDocument() {
return mSmilDocument;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (LOCAL_LOGV) {
Timber.v("SmilContentHandler.startElement. Creating element " + localName);
}
Element element = mSmilDocument.createElement(localName);
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
if (LOCAL_LOGV) {
Timber.v("Attribute " + i +
" lname = " + attributes.getLocalName(i) +
" value = " + attributes.getValue(i));
}
element.setAttribute(attributes.getLocalName(i),
attributes.getValue(i));
}
}
if (LOCAL_LOGV) {
Timber.v("Appending " + localName + " to " + mCurrentNode.getNodeName());
}
mCurrentNode.appendChild(element);
mCurrentNode = element;
}
@Override
public void endElement(String uri, String localName, String qName) {
if (LOCAL_LOGV) {
Timber.v("SmilContentHandler.endElement. localName " + localName);
}
mCurrentNode = mCurrentNode.getParentNode();
}
@Override
public void characters(char[] ch, int start, int length) {
if (LOCAL_LOGV) {
Timber.v("SmilContentHandler.characters. ch = " + new String(ch, start, length));
}
}
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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 com.android.mms.dom.smil.parser;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.smil.SMILDocument;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import com.google.android.mms.MmsException;
public class SmilXmlParser {
private XMLReader mXmlReader;
private SmilContentHandler mContentHandler;
public SmilXmlParser() throws MmsException {
//FIXME: Now we don't have the SAXParser wrapped inside,
// use the Driver class temporarily.
System.setProperty("org.xml.sax.driver", "org.xmlpull.v1.sax2.Driver");
try {
mXmlReader = XMLReaderFactory.createXMLReader();
mContentHandler = new SmilContentHandler();
mXmlReader.setContentHandler(mContentHandler);
} catch (SAXException e) {
throw new MmsException(e);
}
}
public SMILDocument parse(InputStream in) throws IOException, SAXException {
mContentHandler.reset();
mXmlReader.parse(new InputSource(in));
SMILDocument doc = mContentHandler.getSmilDocument();
validateDocument(doc);
return doc;
}
private void validateDocument(SMILDocument doc) {
/*
* Calling getBody() will create "smil", "head", and "body" elements if they
* are not present. It will also initialize the SequentialTimeElementContainer
* member of SMILDocument, which could not be set on creation of the document.
* @see com.android.mms.dom.smil.SmilDocumentImpl#getBody()
*/
doc.getBody();
/*
* Calling getLayout() will create "layout" element if it is not present.
* @see com.android.mms.dom.smil.SmilDocumentImpl#getLayout()
*/
doc.getLayout();
}
}
@@ -16,13 +16,6 @@
package com.android.mms.dom.smil.parser; package com.android.mms.dom.smil.parser;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import timber.log.Timber;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -30,7 +23,16 @@ import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.io.Writer; import java.io.Writer;
import timber.log.Timber;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
public class SmilXmlSerializer { public class SmilXmlSerializer {
private static final String TAG = "SmilXmlSerializer";
public static void serialize(SMILDocument smilDoc, OutputStream out) { public static void serialize(SMILDocument smilDoc, OutputStream out) {
try { try {
@@ -39,9 +41,9 @@ public class SmilXmlSerializer {
writeElement(writer, smilDoc.getDocumentElement()); writeElement(writer, smilDoc.getDocumentElement());
writer.flush(); writer.flush();
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
Timber.e(e, "exception thrown"); Timber.e("exception thrown", e);
} catch (IOException e) { } catch (IOException e) {
Timber.e(e, "exception thrown"); Timber.e("exception thrown", e);
} }
} }
@@ -16,10 +16,14 @@
package com.android.mms.layout; package com.android.mms.layout;
import com.android.mms.logs.LogTag;
import android.content.Context; import android.content.Context;
import timber.log.Timber; import timber.log.Timber;
public class HVGALayoutParameters implements LayoutParameters { public class HVGALayoutParameters implements LayoutParameters {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGV = false;
private int mType = -1; private int mType = -1;
+3
View File
@@ -16,6 +16,8 @@
package com.android.mms.layout; package com.android.mms.layout;
import com.android.mms.logs.LogTag;
import android.content.Context; import android.content.Context;
import android.content.res.Configuration; import android.content.res.Configuration;
import timber.log.Timber; import timber.log.Timber;
@@ -24,6 +26,7 @@ import timber.log.Timber;
* MMS presentation layout management. * MMS presentation layout management.
*/ */
public class LayoutManager { public class LayoutManager {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false; private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGV = false;
@@ -0,0 +1,84 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.logs;
import timber.log.Timber;
public class LogTag {
public static final String TAG = "Mms";
public static final String TRANSACTION = TAG;
public static final String APP = TAG;
public static final String THREAD_CACHE = TAG;
public static final String THUMBNAIL_CACHE = TAG;
public static final String PDU_CACHE = TAG;
public static final String WIDGET = TAG;
public static final String CONTACT = TAG;
/**
* Log tag for enabling/disabling StrictMode violation log.
* To enable: adb shell setprop log.tag.Mms:strictmode DEBUG
*/
public static final String STRICT_MODE_TAG = TAG;
public static final boolean VERBOSE = false;
public static final boolean SEVERE_WARNING = true; // Leave this true
private static final boolean SHOW_SEVERE_WARNING_DIALOG = false; // Set to false before ship
public static final boolean DEBUG_SEND = false; // Set to false before ship
public static final boolean DEBUG_DUMP = false; // Set to false before ship
public static final boolean ALLOW_DUMP_IN_LOGS = false; // Set to false before ship
private static String prettyArray(String[] array) {
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder("[");
int len = array.length-1;
for (int i = 0; i < len; i++) {
sb.append(array[i]);
sb.append(", ");
}
sb.append(array[len]);
sb.append("]");
return sb.toString();
}
private static String logFormat(String format, Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof String[]) {
args[i] = prettyArray((String[])args[i]);
}
}
String s = String.format(format, args);
s = "[" + Thread.currentThread().getId() + "] " + s;
return s;
}
public static void debug(String format, Object... args) {
Timber.d(logFormat(format, args));
}
public static void warn(String format, Object... args) {
Timber.w(logFormat(format, args));
}
public static void error(String format, Object... args) {
Timber.e(logFormat(format, args));
}
}
@@ -0,0 +1,242 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* 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 com.android.mms.service_alt;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.NetworkUtilsHelper;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.text.TextUtils;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.service_alt.exception.ApnException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* APN settings used for MMS transactions
*/
public class ApnSettings {
private static final String TAG = "ApnSettings";
// MMSC URL
private final String mServiceCenter;
// MMSC proxy address
private final String mProxyAddress;
// MMSC proxy port
private final int mProxyPort;
// Debug text for this APN: a concatenation of interesting columns of this APN
private final String mDebugText;
private static final String[] APN_PROJECTION = {
Telephony.Carriers.TYPE,
Telephony.Carriers.MMSC,
Telephony.Carriers.MMSPROXY,
Telephony.Carriers.MMSPORT,
Telephony.Carriers.NAME,
Telephony.Carriers.APN,
Telephony.Carriers.BEARER,
Telephony.Carriers.PROTOCOL,
Telephony.Carriers.ROAMING_PROTOCOL,
Telephony.Carriers.AUTH_TYPE,
Telephony.Carriers.MVNO_TYPE,
Telephony.Carriers.MVNO_MATCH_DATA,
Telephony.Carriers.PROXY,
Telephony.Carriers.PORT,
Telephony.Carriers.SERVER,
Telephony.Carriers.USER,
Telephony.Carriers.PASSWORD,
};
private static final int COLUMN_TYPE = 0;
private static final int COLUMN_MMSC = 1;
private static final int COLUMN_MMSPROXY = 2;
private static final int COLUMN_MMSPORT = 3;
private static final int COLUMN_NAME = 4;
private static final int COLUMN_APN = 5;
private static final int COLUMN_BEARER = 6;
private static final int COLUMN_PROTOCOL = 7;
private static final int COLUMN_ROAMING_PROTOCOL = 8;
private static final int COLUMN_AUTH_TYPE = 9;
private static final int COLUMN_MVNO_TYPE = 10;
private static final int COLUMN_MVNO_MATCH_DATA = 11;
private static final int COLUMN_PROXY = 12;
private static final int COLUMN_PORT = 13;
private static final int COLUMN_SERVER = 14;
private static final int COLUMN_USER = 15;
private static final int COLUMN_PASSWORD = 16;
/**
* Load APN settings from system
*
* @param context
* @param apnName the optional APN name to match
*/
public static ApnSettings load(Context context, String apnName, int subId)
throws ApnException {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String mmsc = sharedPrefs.getString("mmsc_url", "");
if (!TextUtils.isEmpty(mmsc)) {
String mmsProxy = sharedPrefs.getString("mms_proxy", "");
String mmsPort = sharedPrefs.getString("mms_port", "");
return new ApnSettings(mmsc, mmsProxy, parsePort(mmsPort), "Default from settings");
}
Timber.v("ApnSettings: apnName " + apnName);
// TODO: CURRENT semantics is currently broken in telephony. Revive this when it is fixed.
//String selection = Telephony.Carriers.CURRENT + " IS NOT NULL";
String selection = null;
String[] selectionArgs = null;
apnName = apnName != null ? apnName.trim() : null;
if (!TextUtils.isEmpty(apnName)) {
//selection += " AND " + Telephony.Carriers.APN + "=?";
selection = Telephony.Carriers.APN + "=?";
selectionArgs = new String[]{ apnName };
}
Cursor cursor = null;
try {
cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "/subId/" + subId),
APN_PROJECTION,
selection,
selectionArgs,
null/*sortOrder*/);
if (cursor != null) {
String mmscUrl = null;
String proxyAddress = null;
int proxyPort = -1;
while (cursor.moveToNext()) {
// Read values from APN settings
if (isValidApnType(
cursor.getString(COLUMN_TYPE), "mms")) {
mmscUrl = trimWithNullCheck(cursor.getString(COLUMN_MMSC));
if (TextUtils.isEmpty(mmscUrl)) {
continue;
}
mmscUrl = NetworkUtilsHelper.trimV4AddrZeros(mmscUrl);
try {
new URI(mmscUrl);
} catch (URISyntaxException e) {
throw new ApnException("Invalid MMSC url " + mmscUrl);
}
proxyAddress = trimWithNullCheck(cursor.getString(COLUMN_MMSPROXY));
if (!TextUtils.isEmpty(proxyAddress)) {
proxyAddress = NetworkUtilsHelper.trimV4AddrZeros(proxyAddress);
final String portString =
trimWithNullCheck(cursor.getString(COLUMN_MMSPORT));
if (portString != null) {
try {
proxyPort = Integer.parseInt(portString);
} catch (NumberFormatException e) {
Timber.e("Invalid port " + portString);
throw new ApnException("Invalid port " + portString);
}
}
}
return new ApnSettings(
mmscUrl, proxyAddress, proxyPort, getDebugText(cursor));
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return new ApnSettings("", "", 80, "Failed to find APNs :(");
}
private static String getDebugText(Cursor cursor) {
final StringBuilder sb = new StringBuilder();
sb.append("APN [");
for (int i = 0; i < cursor.getColumnCount(); i++) {
final String name = cursor.getColumnName(i);
final String value = cursor.getString(i);
if (TextUtils.isEmpty(value)) {
continue;
}
if (i > 0) {
sb.append(' ');
}
sb.append(name).append('=').append(value);
}
sb.append("]");
return sb.toString();
}
private static String trimWithNullCheck(String value) {
return value != null ? value.trim() : null;
}
public ApnSettings(String mmscUrl, String proxyAddr, int proxyPort, String debugText) {
mServiceCenter = mmscUrl;
mProxyAddress = proxyAddr;
mProxyPort = proxyPort;
mDebugText = debugText;
}
public String getMmscUrl() {
return mServiceCenter;
}
public String getProxyAddress() {
return mProxyAddress;
}
public int getProxyPort() {
return mProxyPort;
}
public boolean isProxySet() {
return !TextUtils.isEmpty(mProxyAddress);
}
private static boolean isValidApnType(String types, String requestType) {
// If APN type is unspecified, assume APN_TYPE_ALL.
if (TextUtils.isEmpty(types)) {
return true;
}
for (String type : types.split(",")) {
type = type.trim();
if (type.equals(requestType) || type.equals("*")) {
return true;
}
}
return false;
}
private static int parsePort(String port) {
if (TextUtils.isEmpty(port)) {
return 80;
} else {
return Integer.parseInt(port);
}
}
public String toString() {
return mDebugText;
}
}
+125 -28
View File
@@ -27,7 +27,9 @@ import android.os.Binder;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Telephony; import android.provider.Telephony;
import android.text.TextUtils; import android.text.TextUtils;
import timber.log.Timber;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.google.android.mms.MmsException; import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu; import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders; import com.google.android.mms.pdu_alt.PduHeaders;
@@ -38,30 +40,29 @@ import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.send_message.BroadcastUtils; import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Transaction; import com.klinker.android.send_message.Transaction;
import timber.log.Timber;
/** /**
* Request to download an MMS * Request to download an MMS
*/ */
public class DownloadRequest extends MmsRequest { public class DownloadRequest extends MmsRequest {
private static final String TAG = "DownloadRequest";
private static final String LOCATION_SELECTION = private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?"; Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
static final String[] PROJECTION = new String[]{ static final String[] PROJECTION = new String[] {
Telephony.Mms.CONTENT_LOCATION Telephony.Mms.CONTENT_LOCATION
}; };
// The indexes of the columns which must be consistent with above PROJECTION. // The indexes of the columns which must be consistent with above PROJECTION.
static final int COLUMN_CONTENT_LOCATION = 0; static final int COLUMN_CONTENT_LOCATION = 0;
private final String mLocationUrl; private final String mLocationUrl;
private final PendingIntent mDownloadedIntent; private final PendingIntent mDownloadedIntent;
private final Uri mContentUri; private final Uri mContentUri;
public DownloadRequest(RequestManager manager, int subId, String locationUrl, public DownloadRequest(RequestManager manager, int subId, String locationUrl,
Uri contentUri, PendingIntent downloadedIntent, String creator, Uri contentUri, PendingIntent downloadedIntent, String creator,
Bundle configOverrides, Context context) throws MmsException { Bundle configOverrides, Context context) throws MmsException {
super(manager, subId, creator, configOverrides); super(manager, subId, creator, configOverrides);
if (locationUrl == null) { if (locationUrl == null) {
@@ -74,6 +75,44 @@ public class DownloadRequest extends MmsRequest {
mContentUri = contentUri; mContentUri = contentUri;
} }
@Override
protected byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException {
final MmsHttpClient mmsHttpClient = netMgr.getOrCreateHttpClient();
if (mmsHttpClient == null) {
Timber.e("MMS network is not ready!");
throw new MmsHttpException(0/*statusCode*/, "MMS network is not ready");
}
return mmsHttpClient.execute(
mLocationUrl,
null/*pud*/,
MmsHttpClient.METHOD_GET,
apn.isProxySet(),
apn.getProxyAddress(),
apn.getProxyPort(),
mMmsConfig);
}
@Override
protected PendingIntent getPendingIntent() {
return mDownloadedIntent;
}
@Override
protected int getQueueType() {
return 1;
}
@Override
protected Uri persistIfRequired(Context context, int result, byte[] response) {
if (!mRequestManager.getAutoPersistingPref()) {
notifyOfDownload(context);
return null;
}
return persist(context, response, mMmsConfig, mLocationUrl, mSubId, mCreator);
}
public static Uri persist(Context context, byte[] response, MmsConfig.Overridden mmsConfig, public static Uri persist(Context context, byte[] response, MmsConfig.Overridden mmsConfig,
String locationUrl, int subId, String creator) { String locationUrl, int subId, String creator) {
// Let any mms apps running as secondary user know that a new mms has been downloaded. // Let any mms apps running as secondary user know that a new mms has been downloaded.
@@ -130,19 +169,20 @@ public class DownloadRequest extends MmsRequest {
// } // }
// Store the downloaded message // Store the downloaded message
final PduPersister persister = PduPersister.getPduPersister(context); final PduPersister persister = PduPersister.getPduPersister(context);
final Uri messageUri = persister.persist(pdu, Telephony.Mms.Inbox.CONTENT_URI, PduPersister.DUMMY_THREAD_ID, true, true, null); final Uri messageUri = persister.persist(
pdu,
Telephony.Mms.Inbox.CONTENT_URI,
true/*createThreadId*/,
true/*groupMmsEnabled*/,
null/*preOpenedFiles*/,
subId);
if (messageUri == null) { if (messageUri == null) {
Timber.e("DownloadRequest.persistIfRequired: can not persist message"); Timber.e("DownloadRequest.persistIfRequired: can not persist message");
return null; return null;
} }
// Update some of the properties of the message // Update some of the properties of the message
final ContentValues values = new ContentValues(); final ContentValues values = new ContentValues();
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L); values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
try {
values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
}
values.put(Telephony.Mms.READ, 0); values.put(Telephony.Mms.READ, 0);
values.put(Telephony.Mms.SEEN, 0); values.put(Telephony.Mms.SEEN, 0);
if (!TextUtils.isEmpty(creator)) { if (!TextUtils.isEmpty(creator)) {
@@ -154,30 +194,52 @@ public class DownloadRequest extends MmsRequest {
} }
try { try {
context.getContentResolver().update(messageUri, values, null, null); values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (SQLiteException e) { } catch (Exception e) {
// On MIUI and a couple other devices, the above call will fail and say `no such column: sub_id` }
// If before making that call, we check to see if the sub_id column is available for messageUri, we will
// find that it is available, and yet the update call will still fail. So - there's no way we can know try {
// in advance that it will fail, and we have to just try again int rowsUpdated = SqliteWrapper.update(
if (values.containsKey(Telephony.Mms.SUBSCRIPTION_ID)) { context,
context.getContentResolver(),
messageUri,
values,
null/*where*/,
null/*selectionArg*/);
if (rowsUpdated != 1) {
Timber.e("DownloadRequest.persistIfRequired: can not update message");
}
} catch (SQLiteException ex) {
// if the exception says no such column like sub_id, ignore this value and try update
if (ex.getMessage().contains("no such column: sub_id")) {
// ignore this column and proceed.
values.remove(Telephony.Mms.SUBSCRIPTION_ID); values.remove(Telephony.Mms.SUBSCRIPTION_ID);
context.getContentResolver().update(messageUri, values, null, null); int rowsUpdated = SqliteWrapper.update(context, context.getContentResolver(), messageUri,
values, null/*where*/, null/*selectionArg*/);
Timber.i("DownloadRequest.persistIfRequired: updated " + rowsUpdated + " message without sub_id info");
} else { } else {
throw e; throw ex;
} }
} }
// Delete the corresponding NotificationInd // Delete the corresponding NotificationInd
SqliteWrapper.delete(context, context.getContentResolver(), Telephony.Mms.CONTENT_URI, LOCATION_SELECTION, SqliteWrapper.delete(context,
new String[]{Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND), locationUrl}); context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
locationUrl
});
return messageUri; return messageUri;
} catch (MmsException e) { } catch (MmsException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not persist message"); Timber.e("DownloadRequest.persistIfRequired: can not persist message", e);
} catch (SQLiteException e) { } catch (SQLiteException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not update message"); Timber.e("DownloadRequest.persistIfRequired: can not update message", e);
} catch (RuntimeException e) { } catch (RuntimeException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not parse response"); Timber.e("DownloadRequest.persistIfRequired: can not parse response", e);
} finally { } finally {
Binder.restoreCallingIdentity(identity); Binder.restoreCallingIdentity(identity);
} }
@@ -227,6 +289,41 @@ public class DownloadRequest extends MmsRequest {
// } // }
} }
/**
* Transfer the received response to the caller (for download requests write to content uri)
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
*/
@Override
protected boolean transferResponse(Intent fillIn, final byte[] response) {
return mRequestManager.writePduToContentUri(mContentUri, response);
}
@Override
protected boolean prepareForHttpRequest() {
return true;
}
/**
* Try downloading via the carrier app.
*
* @param context The context
* @param carrierMessagingServicePackage The carrier messaging service handling the download
*/
public void tryDownloadingByCarrierApp(Context context, String carrierMessagingServicePackage) {
// final CarrierDownloadManager carrierDownloadManger = new CarrierDownloadManager();
// final CarrierDownloadCompleteCallback downloadCallback =
// new CarrierDownloadCompleteCallback(context, carrierDownloadManger);
// carrierDownloadManger.downloadMms(context, carrierMessagingServicePackage,
// downloadCallback);
}
@Override
protected void revokeUriPermission(Context context) {
context.revokeUriPermission(mContentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
private String getContentLocation(Context context, Uri uri) private String getContentLocation(Context context, Uri uri)
throws MmsException { throws MmsException {
Cursor cursor = android.database.sqlite.SqliteWrapper.query(context, context.getContentResolver(), Cursor cursor = android.database.sqlite.SqliteWrapper.query(context, context.getContentResolver(),
@@ -249,10 +346,10 @@ public class DownloadRequest extends MmsRequest {
private static Long getId(Context context, String location) { private static Long getId(Context context, String location) {
String selection = Telephony.Mms.CONTENT_LOCATION + " = ?"; String selection = Telephony.Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[]{location}; String[] selectionArgs = new String[] { location };
Cursor c = android.database.sqlite.SqliteWrapper.query( Cursor c = android.database.sqlite.SqliteWrapper.query(
context, context.getContentResolver(), context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI, new String[]{Telephony.Mms._ID}, Telephony.Mms.CONTENT_URI, new String[] { Telephony.Mms._ID },
selection, selectionArgs, null); selection, selectionArgs, null);
if (c != null) { if (c != null) {
try { try {
+33 -16
View File
@@ -24,8 +24,9 @@ import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Base64; import android.util.Base64;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.klinker.android.send_message.R; import com.klinker.android.send_message.R;
import timber.log.Timber;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@@ -44,6 +45,7 @@ import java.util.concurrent.ConcurrentHashMap;
* 4. Add key/value for relevant mms_config.xml of a specific carrier (mcc/mnc) * 4. Add key/value for relevant mms_config.xml of a specific carrier (mcc/mnc)
*/ */
public class MmsConfig { public class MmsConfig {
private static final String TAG = "MmsConfig";
private static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile"; private static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile";
@@ -336,11 +338,16 @@ public class MmsConfig {
final TelephonyManager telephonyManager = final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
mUserAgent = telephonyManager.getMmsUserAgent(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mUaProfUrl = telephonyManager.getMmsUAProfUrl(); mUserAgent = telephonyManager.getMmsUserAgent();
// defaults for nexus 6, seems to work well. mUaProfUrl = telephonyManager.getMmsUAProfUrl();
//mUserAgent = "nexus6"; // defaults for nexus 6, seems to work well.
//mUaProfUrl = "http://uaprof.motorola.com/phoneconfig/nexus6/Profile/nexus6.rdf"; //mUserAgent = "nexus6";
//mUaProfUrl = "http://uaprof.motorola.com/phoneconfig/nexus6/Profile/nexus6.rdf";
} else {
mUserAgent = "Android Messaging";
mUaProfUrl = "http://www.gstatic.com/android/hangouts/hangouts_mms_ua_profile.xml";
}
} }
private void loadFromResources(Context context) { private void loadFromResources(Context context) {
@@ -551,11 +558,15 @@ public class MmsConfig {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService( final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE); Context.TELEPHONY_SERVICE);
try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
Method method = telephonyManager.getClass().getMethod("getLine1NumberForSubscriber", int.class);
return (String) method.invoke(telephonyManager, subId);
} catch (Exception e) {
return telephonyManager.getLine1Number(); return telephonyManager.getLine1Number();
} else {
try {
Method method = telephonyManager.getClass().getMethod("getLine1NumberForSubscriber", int.class);
return (String) method.invoke(telephonyManager, subId);
} catch (Exception e) {
return telephonyManager.getLine1Number();
}
} }
} }
@@ -577,15 +588,21 @@ public class MmsConfig {
String nai = ""; String nai = "";
try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
Method method = telephonyManager.getClass().getMethod("getNai", int.class);
Method getSlotId = SubscriptionManager.class.getMethod("getSlotId", int.class);
nai = (String) method.invoke(telephonyManager, getSlotId.invoke(null, subId));
} catch (Exception e) {
nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai"); nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai");
} else {
try {
Method method = telephonyManager.getClass().getMethod("getNai", int.class);
Method getSlotId = SubscriptionManager.class.getMethod("getSlotId", int.class);
nai = (String) method.invoke(telephonyManager, getSlotId.invoke(null, subId));
} catch (Exception e) {
nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai");
}
} }
Timber.v("MmsConfig.getNai: nai=" + nai); if (Timber_isLoggable(TAG, Log.VERBOSE)) {
Timber.v("MmsConfig.getNai: nai=" + nai);
}
if (!TextUtils.isEmpty(nai)) { if (!TextUtils.isEmpty(nai)) {
String naiSuffix = getNaiSuffix(); String naiSuffix = getNaiSuffix();
+45 -37
View File
@@ -37,6 +37,7 @@ import java.util.Map;
* *
*/ */
public class MmsConfigManager { public class MmsConfigManager {
private static final String TAG = "MmsConfigManager";
private static volatile MmsConfigManager sInstance = new MmsConfigManager(); private static volatile MmsConfigManager sInstance = new MmsConfigManager();
@@ -73,19 +74,24 @@ public class MmsConfigManager {
public void init(final Context context) { public void init(final Context context) {
mContext = context; mContext = context;
mSubscriptionManager = SubscriptionManager.from(context); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mSubscriptionManager = SubscriptionManager.from(context);
// TODO: When this object "finishes" we should unregister. // TODO: When this object "finishes" we should unregister.
IntentFilter intentFilterLoaded = new IntentFilter("LOADED"); IntentFilter intentFilterLoaded =
new IntentFilter("LOADED");
try { try {
context.registerReceiver(mReceiver, intentFilterLoaded); context.registerReceiver(mReceiver, intentFilterLoaded);
} catch (Exception e) { } catch (Exception e) {
}
load(context);
} else {
load(context);
} }
load(context);
// TODO: When this object "finishes" we should unregister by invoking // TODO: When this object "finishes" we should unregister by invoking
// SubscriptionManager.getInstance(mContext).unregister(mOnSubscriptionsChangedListener); // SubscriptionManager.getInstance(mContext).unregister(mOnSubscriptionsChangedListener);
// This is not strictly necessary because it will be unregistered if the // This is not strictly necessary because it will be unregistered if the
@@ -146,37 +152,39 @@ public class MmsConfigManager {
* *
*/ */
private void load(Context context) { private void load(Context context) {
List<SubscriptionInfo> subs = mSubscriptionManager.getActiveSubscriptionInfoList(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
if (subs == null || subs.size() < 1) { List<SubscriptionInfo> subs = mSubscriptionManager.getActiveSubscriptionInfoList();
Timber.e("MmsConfigManager.load -- empty getActiveSubInfoList"); if (subs == null || subs.size() < 1) {
return; Timber.e("MmsConfigManager.load -- empty getActiveSubInfoList");
} return;
// Load all the mms_config.xml files in a separate map and then swap with the
// real map at the end so we don't block anyone sync'd on the real map.
final Map<Integer, MmsConfig> newConfigMap = new ArrayMap<Integer, MmsConfig>();
for (SubscriptionInfo sub : subs) {
Configuration configuration = new Configuration();
if (sub.getMcc() == 0 && sub.getMnc() == 0) {
Configuration config = mContext.getResources().getConfiguration();
configuration.mcc = config.mcc;
configuration.mnc = config.mnc;
Timber.i("MmsConfigManager.load -- no mcc/mnc for sub: " + sub +
" using mcc/mnc from main context: " + configuration.mcc + "/" +
configuration.mnc);
} else {
Timber.i("MmsConfigManager.load -- mcc/mnc for sub: " + sub);
configuration.mcc = sub.getMcc();
configuration.mnc = sub.getMnc();
} }
Context subContext = context.createConfigurationContext(configuration); // Load all the mms_config.xml files in a separate map and then swap with the
// real map at the end so we don't block anyone sync'd on the real map.
final Map<Integer, MmsConfig> newConfigMap = new ArrayMap<Integer, MmsConfig>();
for (SubscriptionInfo sub : subs) {
Configuration configuration = new Configuration();
if (sub.getMcc() == 0 && sub.getMnc() == 0) {
Configuration config = mContext.getResources().getConfiguration();
configuration.mcc = config.mcc;
configuration.mnc = config.mnc;
Timber.i("MmsConfigManager.load -- no mcc/mnc for sub: " + sub +
" using mcc/mnc from main context: " + configuration.mcc + "/" +
configuration.mnc);
} else {
Timber.i("MmsConfigManager.load -- mcc/mnc for sub: " + sub);
int subId = sub.getSubscriptionId(); configuration.mcc = sub.getMcc();
newConfigMap.put(subId, new MmsConfig(subContext, subId)); configuration.mnc = sub.getMnc();
} }
synchronized (mSubIdConfigMap) { Context subContext = context.createConfigurationContext(configuration);
mSubIdConfigMap.clear();
mSubIdConfigMap.putAll(newConfigMap); int subId = sub.getSubscriptionId();
newConfigMap.put(subId, new MmsConfig(subContext, subId));
}
synchronized (mSubIdConfigMap) {
mSubIdConfigMap.clear();
mSubIdConfigMap.putAll(newConfigMap);
}
} }
} }
@@ -16,9 +16,10 @@
package com.android.mms.service_alt; package com.android.mms.service_alt;
import android.content.ContentValues;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
import android.content.ContentValues;
import timber.log.Timber; import timber.log.Timber;
import java.io.IOException; import java.io.IOException;
@@ -27,6 +28,7 @@ import java.io.IOException;
* XML processor for mms_config.xml * XML processor for mms_config.xml
*/ */
public class MmsConfigXmlProcessor { public class MmsConfigXmlProcessor {
private static final String TAG = "MmsConfigXmlProcessor";
public interface MmsConfigHandler { public interface MmsConfigHandler {
public void process(String key, String value, String type); public void process(String key, String value, String type);
@@ -91,9 +93,9 @@ public class MmsConfigXmlProcessor {
processMmsConfig(); processMmsConfig();
} }
} catch (IOException e) { } catch (IOException e) {
Timber.e(e, "MmsConfigXmlProcessor: I/O failure " + e); Timber.e("MmsConfigXmlProcessor: I/O failure " + e, e);
} catch (XmlPullParserException e) { } catch (XmlPullParserException e) {
Timber.e(e, "MmsConfigXmlProcessor: parsing failure " + e); Timber.e("MmsConfigXmlProcessor: parsing failure " + e, e);
} }
} }
@@ -131,7 +133,7 @@ public class MmsConfigXmlProcessor {
} }
return mLogStringBuilder.toString(); return mLogStringBuilder.toString();
} catch (XmlPullParserException e) { } catch (XmlPullParserException e) {
Timber.e(e, "xmlParserDebugContext: " + e); Timber.e("xmlParserDebugContext: " + e, e);
} }
} }
return "Unknown"; return "Unknown";
+56 -14
View File
@@ -18,6 +18,8 @@ package com.android.mms.service_alt;
import android.content.Context; import android.content.Context;
import android.text.TextUtils; import android.text.TextUtils;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.service_alt.exception.MmsHttpException; import com.android.mms.service_alt.exception.MmsHttpException;
import com.squareup.okhttp.ConnectionPool; import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.ConnectionSpec; import com.squareup.okhttp.ConnectionSpec;
@@ -28,11 +30,7 @@ import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.Internal; import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.huc.HttpURLConnectionImpl; import com.squareup.okhttp.internal.huc.HttpURLConnectionImpl;
import com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl; import com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl;
import timber.log.Timber;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -55,11 +53,15 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
/** /**
* MMS HTTP client for sending and downloading MMS messages * MMS HTTP client for sending and downloading MMS messages
*/ */
public class MmsHttpClient { public class MmsHttpClient {
private static final String TAG = "MmsHttpClient";
public static final String METHOD_POST = "POST"; public static final String METHOD_POST = "POST";
public static final String METHOD_GET = "GET"; public static final String METHOD_GET = "GET";
@@ -116,7 +118,7 @@ public class MmsHttpClient {
public byte[] execute(String urlString, byte[] pdu, String method, boolean isProxySet, public byte[] execute(String urlString, byte[] pdu, String method, boolean isProxySet,
String proxyHost, int proxyPort, MmsConfig.Overridden mmsConfig) String proxyHost, int proxyPort, MmsConfig.Overridden mmsConfig)
throws MmsHttpException { throws MmsHttpException {
Timber.d("HTTP: " + method + " " + urlString Timber.d("HTTP: " + method + " " + redactUrlForNonVerbose(urlString)
+ (isProxySet ? (", proxy=" + proxyHost + ":" + proxyPort) : "") + (isProxySet ? (", proxy=" + proxyHost + ":" + proxyPort) : "")
+ ", PDU size=" + (pdu != null ? pdu.length : 0)); + ", PDU size=" + (pdu != null ? pdu.length : 0));
checkMethod(method); checkMethod(method);
@@ -165,22 +167,29 @@ public class MmsHttpClient {
connection.setRequestProperty(HEADER_CONTENT_TYPE, connection.setRequestProperty(HEADER_CONTENT_TYPE,
HEADER_VALUE_CONTENT_TYPE_WITHOUT_CHARSET); HEADER_VALUE_CONTENT_TYPE_WITHOUT_CHARSET);
} }
logHttpHeaders(connection.getRequestProperties()); if (Timber_isLoggable(TAG, Log.VERBOSE)) {
logHttpHeaders(connection.getRequestProperties());
}
connection.setFixedLengthStreamingMode(pdu.length); connection.setFixedLengthStreamingMode(pdu.length);
// Sending request body // Sending request body
final OutputStream out = new BufferedOutputStream(connection.getOutputStream()); final OutputStream out =
new BufferedOutputStream(connection.getOutputStream());
out.write(pdu); out.write(pdu);
out.flush(); out.flush();
out.close(); out.close();
} else if (METHOD_GET.equals(method)) { } else if (METHOD_GET.equals(method)) {
logHttpHeaders(connection.getRequestProperties()); if (Timber_isLoggable(TAG, Log.VERBOSE)) {
logHttpHeaders(connection.getRequestProperties());
}
connection.setRequestMethod(METHOD_GET); connection.setRequestMethod(METHOD_GET);
} }
// Get response // Get response
final int responseCode = connection.getResponseCode(); final int responseCode = connection.getResponseCode();
final String responseMessage = connection.getResponseMessage(); final String responseMessage = connection.getResponseMessage();
Timber.d("HTTP: " + responseCode + " " + responseMessage); Timber.d("HTTP: " + responseCode + " " + responseMessage);
logHttpHeaders(connection.getHeaderFields()); if (Timber_isLoggable(TAG, Log.VERBOSE)) {
logHttpHeaders(connection.getHeaderFields());
}
if (responseCode / 100 != 2) { if (responseCode / 100 != 2) {
throw new MmsHttpException(responseCode, responseMessage); throw new MmsHttpException(responseCode, responseMessage);
} }
@@ -197,13 +206,15 @@ public class MmsHttpClient {
+ (responseBody != null ? responseBody.length : 0)); + (responseBody != null ? responseBody.length : 0));
return responseBody; return responseBody;
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
Timber.e(e, "HTTP: invalid URL " + urlString); final String redactedUrl = redactUrlForNonVerbose(urlString);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL " + urlString, e); Timber.e("HTTP: invalid URL " + redactedUrl, e);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL " + redactedUrl, e);
} catch (ProtocolException e) { } catch (ProtocolException e) {
Timber.e(e, "HTTP: invalid URL protocol " + urlString); final String redactedUrl = redactUrlForNonVerbose(urlString);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL protocol " + urlString, e); Timber.e("HTTP: invalid URL protocol " + redactedUrl, e);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL protocol " + redactedUrl, e);
} catch (IOException e) { } catch (IOException e) {
Timber.e(e, "HTTP: IO failure"); Timber.e("HTTP: IO failure", e);
throw new MmsHttpException(0/*statusCode*/, e); throw new MmsHttpException(0/*statusCode*/, e);
} finally { } finally {
if (connection != null) { if (connection != null) {
@@ -449,4 +460,35 @@ public class MmsHttpClient {
} }
} }
} }
/**
* Redact the URL for non-VERBOSE logging. Replace url with only the host part and the length
* of the input URL string.
*
* @param urlString
* @return
*/
public static String redactUrlForNonVerbose(String urlString) {
if (Timber_isLoggable(TAG, Log.VERBOSE)) {
// Don't redact for VERBOSE level logging
return urlString;
}
if (TextUtils.isEmpty(urlString)) {
return urlString;
}
String protocol = "http";
String host = "";
try {
final URL url = new URL(urlString);
protocol = url.getProtocol();
host = url.getHost();
} catch (MalformedURLException e) {
// Ignore
}
// Print "http://host[length]"
final StringBuilder sb = new StringBuilder();
sb.append(protocol).append("://").append(host)
.append("[").append(urlString.length()).append("]");
return sb.toString();
}
} }
+19 -10
View File
@@ -20,20 +20,22 @@ import android.content.Context;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.Network; import android.net.Network;
import android.net.NetworkCapabilities; import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest; import android.net.NetworkRequest;
import android.net.NetworkInfo;
import android.net.SSLCertificateSocketFactory; import android.net.SSLCertificateSocketFactory;
import android.os.Build; import android.os.Build;
import android.os.SystemClock; import android.os.SystemClock;
import timber.log.Timber;
import com.android.mms.service_alt.exception.MmsNetworkException; import com.android.mms.service_alt.exception.MmsNetworkException;
import com.squareup.okhttp.ConnectionPool; import com.squareup.okhttp.ConnectionPool;
import timber.log.Timber;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
public class MmsNetworkManager implements com.squareup.okhttp.internal.Network { public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
private static final String TAG = "MmsNetworkManager";
// Timeout used to call ConnectivityManager.requestNetwork // Timeout used to call ConnectivityManager.requestNetwork
private static final int NETWORK_REQUEST_TIMEOUT_MILLIS = 60 * 1000; private static final int NETWORK_REQUEST_TIMEOUT_MILLIS = 60 * 1000;
// Wait timeout for this class, a little bit longer than the above timeout // Wait timeout for this class, a little bit longer than the above timeout
@@ -87,11 +89,18 @@ public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
mSubId = subId; mSubId = subId;
if (!MmsRequest.useWifi(context)) { if (!MmsRequest.useWifi(context)) {
mNetworkRequest = new NetworkRequest.Builder() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) mNetworkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS) .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.setNetworkSpecifier(Integer.toString(mSubId)) .addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.build(); .setNetworkSpecifier(Integer.toString(mSubId))
.build();
} else {
mNetworkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.build();
}
} else { } else {
mNetworkRequest = new NetworkRequest.Builder() mNetworkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
@@ -196,7 +205,7 @@ public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
connectivityManager.requestNetwork( connectivityManager.requestNetwork(
mNetworkRequest, mNetworkCallback); mNetworkRequest, mNetworkCallback);
} catch (SecurityException e) { } catch (SecurityException e) {
Timber.e(e, "permission exception... skipping it for testing purposes"); Timber.e("permission exception... skipping it for testing purposes", e);
permissionError = true; permissionError = true;
} }
} }
@@ -213,7 +222,7 @@ public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
try { try {
connectivityManager.unregisterNetworkCallback(callback); connectivityManager.unregisterNetworkCallback(callback);
} catch (Exception e) { } catch (Exception e) {
Timber.e(e, "couldn't unregister"); Timber.e("couldn't unregister", e);
} }
} }
resetLocked(); resetLocked();
+290
View File
@@ -16,18 +16,34 @@
package com.android.mms.service_alt; package com.android.mms.service_alt;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Settings;
import android.service.carrier.CarrierMessagingService;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import timber.log.Timber;
import com.klinker.android.send_message.Utils; import com.klinker.android.send_message.Utils;
import com.android.mms.service_alt.exception.ApnException;
import com.android.mms.service_alt.exception.MmsHttpException;
/** /**
* Base class for MMS requests. This has the common logic of sending/downloading MMS. * Base class for MMS requests. This has the common logic of sending/downloading MMS.
*/ */
public abstract class MmsRequest { public abstract class MmsRequest {
private static final String TAG = "MmsRequest";
private static final int RETRY_TIMES = 3;
/** /**
* Interface for certain functionalities from MmsService * Interface for certain functionalities from MmsService
@@ -73,6 +89,8 @@ public abstract class MmsRequest {
// MMS config overrides // MMS config overrides
protected Bundle mMmsConfigOverrides; protected Bundle mMmsConfigOverrides;
private boolean mobileDataEnabled;
public MmsRequest(RequestManager requestManager, int subId, String creator, public MmsRequest(RequestManager requestManager, int subId, String creator,
Bundle configOverrides) { Bundle configOverrides) {
mRequestManager = requestManager; mRequestManager = requestManager;
@@ -86,6 +104,192 @@ public abstract class MmsRequest {
return mSubId; return mSubId;
} }
private boolean ensureMmsConfigLoaded() {
if (mMmsConfig == null) {
final MmsConfig config;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
// Not yet retrieved from mms config manager. Try getting it.
config = MmsConfigManager.getInstance().getMmsConfigBySubId(mSubId);
} else {
config = MmsConfigManager.getInstance().getMmsConfig();
}
if (config != null) {
mMmsConfig = new MmsConfig.Overridden(config, mMmsConfigOverrides);
}
}
return mMmsConfig != null;
}
private static boolean inAirplaneMode(final Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
private static boolean isMobileDataEnabled(final Context context, final int subId) {
final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return Utils.isDataEnabled(telephonyManager, subId);
}
private static boolean isDataNetworkAvailable(final Context context, final int subId) {
return !inAirplaneMode(context) && isMobileDataEnabled(context, subId);
}
/**
* Execute the request
*
* @param context The context
* @param networkManager The network manager to use
*/
public void execute(Context context, MmsNetworkManager networkManager) {
int result = SmsManager.MMS_ERROR_UNSPECIFIED;
int httpStatusCode = 0;
byte[] response = null;
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean isWifiEnabled = wifi.isWifiEnabled();
if (!useWifi(context)) {
wifi.setWifiEnabled(false);
}
mobileDataEnabled = Utils.isMobileDataEnabled(context);
Timber.v("mobile data enabled: " + mobileDataEnabled);
if (!mobileDataEnabled && !useWifi(context)) {
Timber.v("mobile data not enabled, so forcing it to enable");
Utils.setMobileDataEnabled(context, true);
}
if (!ensureMmsConfigLoaded()) { // Check mms config
Timber.e("MmsRequest: mms config is not loaded yet");
result = SmsManager.MMS_ERROR_CONFIGURATION_ERROR;
} else if (!prepareForHttpRequest()) { // Prepare request, like reading pdu data from user
Timber.e("MmsRequest: failed to prepare for request");
result = SmsManager.MMS_ERROR_IO_ERROR;
} else if (!isDataNetworkAvailable(context, mSubId)) {
Timber.e("MmsRequest: in airplane mode or mobile data disabled");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
result = SmsManager.MMS_ERROR_NO_DATA_NETWORK;
} else {
result = 8;
}
} else { // Execute
long retryDelaySecs = 2;
// Try multiple times of MMS HTTP request
for (int i = 0; i < RETRY_TIMES; i++) {
try {
try {
networkManager.acquireNetwork();
} catch (Exception e) {
Timber.e("error acquiring network", e);
}
final String apnName = networkManager.getApnName();
try {
ApnSettings apn = null;
try {
apn = ApnSettings.load(context, apnName, mSubId);
} catch (ApnException e) {
// If no APN could be found, fall back to trying without the APN name
if (apnName == null) {
// If the APN name was already null then don't need to retry
throw (e);
}
Timber.i("MmsRequest: No match with APN name:"
+ apnName + ", try with no name");
apn = ApnSettings.load(context, null, mSubId);
}
Timber.i("MmsRequest: using " + apn.toString());
response = doHttp(context, networkManager, apn);
result = Activity.RESULT_OK;
// Success
break;
} finally {
networkManager.releaseNetwork();
}
} catch (ApnException e) {
Timber.e("MmsRequest: APN failure", e);
result = SmsManager.MMS_ERROR_INVALID_APN;
break;
// } catch (MmsNetworkException e) {
// Timber.e("MmsRequest: MMS network acquiring failure", e);
// result = SmsManager.MMS_ERROR_UNABLE_CONNECT_MMS;
// // Retry
} catch (MmsHttpException e) {
Timber.e("MmsRequest: HTTP or network I/O failure", e);
result = SmsManager.MMS_ERROR_HTTP_FAILURE;
httpStatusCode = e.getStatusCode();
// Retry
} catch (Exception e) {
Timber.e("MmsRequest: unexpected failure", e);
result = SmsManager.MMS_ERROR_UNSPECIFIED;
break;
}
try {
Thread.sleep(retryDelaySecs * 1000, 0/*nano*/);
} catch (InterruptedException e) {
}
retryDelaySecs <<= 1;
}
}
if (!mobileDataEnabled) {
Timber.v("setting mobile data back to disabled");
Utils.setMobileDataEnabled(context, false);
}
if (!useWifi(context)) {
wifi.setWifiEnabled(isWifiEnabled);
}
processResult(context, result, response, httpStatusCode);
}
/**
* Process the result of the completed request, including updating the message status
* in database and sending back the result via pending intents.
* @param context The context
* @param result The result code of execution
* @param response The response body
* @param httpStatusCode The optional http status code in case of http failure
*/
public void processResult(Context context, int result, byte[] response, int httpStatusCode) {
final Uri messageUri = persistIfRequired(context, result, response);
// Return MMS HTTP request result via PendingIntent
final PendingIntent pendingIntent = getPendingIntent();
if (pendingIntent != null) {
boolean succeeded = true;
// Extra information to send back with the pending intent
Intent fillIn = new Intent();
if (response != null) {
succeeded = transferResponse(fillIn, response);
}
if (messageUri != null) {
fillIn.putExtra("uri", messageUri.toString());
}
if (result == SmsManager.MMS_ERROR_HTTP_FAILURE && httpStatusCode != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
fillIn.putExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, httpStatusCode);
} else {
fillIn.putExtra("android.telephony.extra.MMS_HTTP_STATUS", httpStatusCode);
}
}
try {
if (!succeeded) {
result = SmsManager.MMS_ERROR_IO_ERROR;
}
pendingIntent.send(context, result, fillIn);
} catch (PendingIntent.CanceledException e) {
Timber.e("MmsRequest: sending pending intent canceled", e);
}
}
revokeUriPermission(context);
}
/** /**
* are we set up to use wifi? if so, send mms over it. * are we set up to use wifi? if so, send mms over it.
*/ */
@@ -102,4 +306,90 @@ public abstract class MmsRequest {
return false; return false;
} }
/**
* Returns true if sending / downloading using the carrier app has failed and completes the
* action using platform API's, otherwise false.
*/
protected boolean maybeFallbackToRegularDelivery(int carrierMessagingAppResult) {
if (carrierMessagingAppResult
== CarrierMessagingService.SEND_STATUS_RETRY_ON_CARRIER_NETWORK
|| carrierMessagingAppResult
== CarrierMessagingService.DOWNLOAD_STATUS_RETRY_ON_CARRIER_NETWORK) {
Timber.d("Sending/downloading MMS by IP failed.");
mRequestManager.addSimRequest(MmsRequest.this);
return true;
} else {
return false;
}
}
/**
* Converts from {@code carrierMessagingAppResult} to a platform result code.
*/
protected static int toSmsManagerResult(int carrierMessagingAppResult) {
switch (carrierMessagingAppResult) {
case CarrierMessagingService.SEND_STATUS_OK:
return Activity.RESULT_OK;
case CarrierMessagingService.SEND_STATUS_RETRY_ON_CARRIER_NETWORK:
return SmsManager.MMS_ERROR_RETRY;
default:
return SmsManager.MMS_ERROR_UNSPECIFIED;
}
}
/**
* Making the HTTP request to MMSC
*
* @param context The context
* @param netMgr The current {@link MmsNetworkManager}
* @param apn The APN setting
* @return The HTTP response data
* @throws MmsHttpException If any network error happens
*/
protected abstract byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException;
/**
* @return The PendingIntent associate with the MMS sending invocation
*/
protected abstract PendingIntent getPendingIntent();
/**
* @return The queue should be used by this request, 0 is sending and 1 is downloading
*/
protected abstract int getQueueType();
/**
* Persist message into telephony if required (i.e. when auto-persisting is on or
* the calling app is non-default sms app for sending)
*
* @param context The context
* @param result The result code of execution
* @param response The response body
* @return The persisted URI of the message or null if we don't persist or fail
*/
protected abstract Uri persistIfRequired(Context context, int result, byte[] response);
/**
* Prepare to make the HTTP request - will download message for sending
* @return true if preparation succeeds (and request can proceed) else false
*/
protected abstract boolean prepareForHttpRequest();
/**
* Transfer the received response to the caller
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
* @return true if response transfer succeeds else false
*/
protected abstract boolean transferResponse(Intent fillIn, byte[] response);
/**
* Revoke the content URI permission granted by the MMS app to the phone package.
*
* @param context The context
*/
protected abstract void revokeUriPermission(Context context);
} }
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* 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 com.android.mms.service_alt;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.util.Log; import timber.log.Timber; // inserted with sed
import com.android.mms.transaction.NotificationTransaction;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.send_message.Settings;
public class MmsRequestManager implements MmsRequest.RequestManager {
private static final String TAG = "MmsRequestManager";
private Context context;
private byte[] pduData;
public MmsRequestManager(Context context) {
this(context, null);
}
public MmsRequestManager(Context context, byte[] pduData) {
this.context = context;
this.pduData = pduData;
}
@Override
public void addSimRequest(MmsRequest request) {
// Do nothing, this will not be invoked ever.
}
@Override
public boolean getAutoPersistingPref() {
return NotificationTransaction.allowAutoDownload(context);
}
@Override
public byte[] readPduFromContentUri(Uri contentUri, int maxSize) {
return pduData;
}
@Override
public boolean writePduToContentUri(Uri contentUri, byte[] response) {
if (response == null || response.length < 1) {
Timber.e("empty response");
return false;
}
try {
// Parse M-Retrieve.conf
RetrieveConf retrieveConf = (RetrieveConf) new PduParser(response).parse();
if (null == retrieveConf) {
throw new MmsException("Invalid M-Retrieve.conf PDU.");
}
Uri msgUri;
boolean group;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
// Store M-Retrieve.conf into Inbox
PduPersister persister = PduPersister.getPduPersister(context);
msgUri = persister.persist(retrieveConf, Telephony.Mms.Inbox.CONTENT_URI, true,
group, null, subId);
// Use local time instead of PDU time
ContentValues values = new ContentValues();
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
values.put(Telephony.Mms.MESSAGE_SIZE, response.length);
try {
// Store PDU time as sent time for received message
values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception e) {
}
SqliteWrapper.update(context, context.getContentResolver(),
msgUri, values, null, null);
// Send ACK to the Proxy-Relay to indicate we have fetched the
// MM successfully.
// Don't mark the transaction as failed if we failed to send it.
// sendAcknowledgeInd(retrieveConf);
} catch (Throwable t) {
Timber.e(TAG, "error", t);
}
return false;
}
}
+4 -1
View File
@@ -18,10 +18,11 @@ package com.android.mms.service_alt;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.TextUtils; import android.text.TextUtils;
import timber.log.Timber;
import com.android.i18n.phonenumbers.NumberParseException; import com.android.i18n.phonenumbers.NumberParseException;
import com.android.i18n.phonenumbers.PhoneNumberUtil; import com.android.i18n.phonenumbers.PhoneNumberUtil;
import com.android.i18n.phonenumbers.Phonenumber; import com.android.i18n.phonenumbers.Phonenumber;
import timber.log.Timber;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Locale; import java.util.Locale;
@@ -31,6 +32,8 @@ import java.util.Locale;
*/ */
public class PhoneUtils { public class PhoneUtils {
private static final String TAG = "PhoneUtils";
/** /**
* Get a canonical national format phone number. If parsing fails, just return the * Get a canonical national format phone number. If parsing fails, just return the
* original number. * original number.
@@ -0,0 +1,231 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* 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 com.android.mms.service_alt;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.text.TextUtils;
import timber.log.Timber;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.SendConf;
import com.google.android.mms.pdu_alt.SendReq;
import com.google.android.mms.util_alt.SqliteWrapper;
/**
* Request to send an MMS
*/
public class SendRequest extends MmsRequest {
private static final String TAG = "SendRequest";
private final Uri mPduUri;
private byte[] mPduData;
private final String mLocationUrl;
private final PendingIntent mSentIntent;
public SendRequest(RequestManager manager, int subId, Uri contentUri, String locationUrl,
PendingIntent sentIntent, String creator, Bundle configOverrides) {
super(manager, subId, creator, configOverrides);
mPduUri = contentUri;
mPduData = null;
mLocationUrl = locationUrl;
mSentIntent = sentIntent;
}
@Override
protected byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException {
final MmsHttpClient mmsHttpClient = netMgr.getOrCreateHttpClient();
if (mmsHttpClient == null) {
Timber.e("MMS network is not ready!");
throw new MmsHttpException(0/*statusCode*/, "MMS network is not ready");
}
return mmsHttpClient.execute(
mLocationUrl != null ? mLocationUrl : apn.getMmscUrl(),
mPduData,
MmsHttpClient.METHOD_POST,
apn.isProxySet(),
apn.getProxyAddress(),
apn.getProxyPort(),
mMmsConfig);
}
@Override
protected PendingIntent getPendingIntent() {
return mSentIntent;
}
@Override
protected int getQueueType() {
return 0;
}
@Override
protected Uri persistIfRequired(Context context, int result, byte[] response) {
Timber.d("SendRequest.persistIfRequired");
if (mPduData == null) {
Timber.e("SendRequest.persistIfRequired: empty PDU");
return null;
}
final long identity = Binder.clearCallingIdentity();
try {
final boolean supportContentDisposition = mMmsConfig.getSupportMmsContentDisposition();
// Persist the request PDU first
GenericPdu pdu = (new PduParser(mPduData, supportContentDisposition)).parse();
if (pdu == null) {
Timber.e("SendRequest.persistIfRequired: can't parse input PDU");
return null;
}
if (!(pdu instanceof SendReq)) {
Timber.d("SendRequest.persistIfRequired: not SendReq");
return null;
}
// final PduPersister persister = PduPersister.getPduPersister(context);
// final Uri messageUri = persister.persist(
// pdu,
// Telephony.Mms.Sent.CONTENT_URI,
// true/*createThreadId*/,
// true/*groupMmsEnabled*/,
// null/*preOpenedFiles*/);
// if (messageUri == null) {
// Timber.e("SendRequest.persistIfRequired: can not persist message");
// return null;
// }
// Update the additional columns based on the send result
final ContentValues values = new ContentValues();
SendConf sendConf = null;
if (response != null && response.length > 0) {
pdu = (new PduParser(response, supportContentDisposition)).parse();
if (pdu != null && pdu instanceof SendConf) {
sendConf = (SendConf) pdu;
}
}
if (result != Activity.RESULT_OK
|| sendConf == null
|| sendConf.getResponseStatus() != PduHeaders.RESPONSE_STATUS_OK) {
// Since we can't persist a message directly into FAILED box,
// we have to update the column after we persist it into SENT box.
// The gap between the state change is tiny so I would not expect
// it to cause any serious problem
// TODO: we should add a "failed" URI for this in MmsProvider?
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_FAILED);
} else {
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT);
}
if (sendConf != null) {
values.put(Telephony.Mms.RESPONSE_STATUS, sendConf.getResponseStatus());
Timber.v("response status: " + sendConf.getResponseStatus());
values.put(Telephony.Mms.MESSAGE_ID,
PduPersister.toIsoString(sendConf.getMessageId()));
}
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
values.put(Telephony.Mms.READ, 1);
values.put(Telephony.Mms.SEEN, 1);
if (!TextUtils.isEmpty(mCreator)) {
values.put(Telephony.Mms.CREATOR, mCreator);
}
if (SubscriptionIdChecker.getInstance(context).canUseSubscriptionId()) {
values.put(Telephony.Mms.SUBSCRIPTION_ID, mSubId);
}
if (SqliteWrapper.update(context, context.getContentResolver(), mPduUri, values,
null/*where*/, null/*selectionArg*/) != 1) {
Timber.e("SendRequest.persistIfRequired: failed to update message");
}
return mPduUri;
// } catch (MmsException e) {
// Timber.e("SendRequest.persistIfRequired: can not persist message", e);
} catch (RuntimeException e) {
Timber.e("SendRequest.persistIfRequired: unexpected parsing failure", e);
} finally {
Binder.restoreCallingIdentity(identity);
}
return null;
}
/**
* Read the pdu from the file descriptor and cache pdu bytes in request
* @return true if pdu read successfully
*/
private boolean readPduFromContentUri() {
if (mPduData != null) {
return true;
}
final int bytesTobeRead = mMmsConfig.getMaxMessageSize();
mPduData = mRequestManager.readPduFromContentUri(mPduUri, bytesTobeRead);
return (mPduData != null);
}
/**
* Transfer the received response to the caller (for send requests the pdu is small and can
* just include bytes as extra in the "returned" intent).
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
*/
@Override
protected boolean transferResponse(Intent fillIn, byte[] response) {
// SendConf pdus are always small and can be included in the intent
if (response != null) {
fillIn.putExtra(SmsManager.EXTRA_MMS_DATA, response);
}
return true;
}
/**
* Read the data from the file descriptor if not yet done
* @return whether data successfully read
*/
@Override
protected boolean prepareForHttpRequest() {
return readPduFromContentUri();
}
/**
* Try sending via the carrier app
*
* @param context the context
* @param carrierMessagingServicePackage the carrier messaging service sending the MMS
*/
public void trySendingByCarrierApp(Context context, String carrierMessagingServicePackage) {
// final CarrierSendManager carrierSendManger = new CarrierSendManager();
// final CarrierSendCompleteCallback sendCallback = new CarrierSendCompleteCallback(
// context, carrierSendManger);
// carrierSendManger.sendMms(context, carrierMessagingServicePackage, sendCallback);
}
@Override
protected void revokeUriPermission(Context context) {
try {
context.revokeUriPermission(mPduUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (NullPointerException e) {
Timber.e("error revoking permissions", e);
}
}
}
@@ -6,34 +6,38 @@ import android.database.Cursor;
import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteException;
import android.os.Build; import android.os.Build;
import android.provider.Telephony; import android.provider.Telephony;
import com.google.android.mms.util_alt.SqliteWrapper;
import timber.log.Timber; import timber.log.Timber;
class SubscriptionIdChecker { import com.google.android.mms.util_alt.SqliteWrapper;
public class SubscriptionIdChecker {
private static final String TAG = "SubscriptionIdChecker";
private static SubscriptionIdChecker sInstance; private static SubscriptionIdChecker sInstance;
private boolean mCanUseSubscriptionId = false; private boolean mCanUseSubscriptionId = false;
// I met a device which does not have Telephony.Mms.SUBSCRIPTION_ID event if it's API Level is 22. // I met a device which does not have Telephony.Mms.SUBSCRIPTION_ID event if it's API Level is 22.
private void check(Context context) { private void check(Context context) {
Cursor c = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
try { Cursor c = null;
c = SqliteWrapper.query(context, context.getContentResolver(), try {
Telephony.Mms.CONTENT_URI, c = SqliteWrapper.query(context, context.getContentResolver(),
new String[]{Telephony.Mms.SUBSCRIPTION_ID}, null, null, null); Telephony.Mms.CONTENT_URI,
if (c != null) { new String[]{Telephony.Mms.SUBSCRIPTION_ID}, null, null, null);
mCanUseSubscriptionId = true; if (c != null) {
} mCanUseSubscriptionId = true;
} catch (SQLiteException e) { }
Timber.e("SubscriptionIdChecker.check() fail"); } catch (SQLiteException e) {
} finally { Timber.e("SubscriptionIdChecker.check() fail");
if (c != null) { } finally {
c.close(); if (c != null) {
c.close();
}
} }
} }
} }
static synchronized SubscriptionIdChecker getInstance(Context context) { public static synchronized SubscriptionIdChecker getInstance(Context context) {
if (sInstance == null) { if (sInstance == null) {
sInstance = new SubscriptionIdChecker(); sInstance = new SubscriptionIdChecker();
sInstance.check(context); sInstance.check(context);
@@ -41,7 +45,7 @@ class SubscriptionIdChecker {
return sInstance; return sInstance;
} }
boolean canUseSubscriptionId() { public boolean canUseSubscriptionId() {
return mCanUseSubscriptionId; return mCanUseSubscriptionId;
} }
} }
@@ -16,6 +16,8 @@
package com.android.mms.transaction; package com.android.mms.transaction;
import com.android.mms.logs.LogTag;
import android.content.Context; import android.content.Context;
import android.util.Config; import android.util.Config;
import timber.log.Timber; import timber.log.Timber;
@@ -24,6 +26,7 @@ import timber.log.Timber;
* Default retry scheme, based on specs. * Default retry scheme, based on specs.
*/ */
public class DefaultRetryScheme extends AbstractRetryScheme { public class DefaultRetryScheme extends AbstractRetryScheme {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false; private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV; private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
+15 -33
View File
@@ -1,27 +1,27 @@
package com.android.mms.transaction; package com.android.mms.transaction;
import android.annotation.TargetApi;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.PowerManager; import android.os.PowerManager;
import android.provider.Telephony;
import android.telephony.SmsManager; import android.telephony.SmsManager;
import android.text.TextUtils; import android.text.TextUtils;
import com.android.mms.MmsConfig; import com.android.mms.MmsConfig;
import timber.log.Timber;
import com.klinker.android.send_message.BroadcastUtils; import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.MmsReceivedReceiver; import com.klinker.android.send_message.MmsReceivedReceiver;
import com.klinker.android.send_message.SmsManagerFactory; import com.klinker.android.send_message.SmsManagerFactory;
import timber.log.Timber;
import java.io.File; import java.io.File;
import java.util.Random; import java.util.Random;
import java.util.UUID; import java.util.UUID;
@@ -32,6 +32,7 @@ import java.util.concurrent.ConcurrentHashMap;
* We should manage to call SMSManager.downloadMultimediaMessage(). * We should manage to call SMSManager.downloadMultimediaMessage().
*/ */
public class DownloadManager { public class DownloadManager {
private static final String TAG = "DownloadManager";
private static DownloadManager ourInstance = new DownloadManager(); private static DownloadManager ourInstance = new DownloadManager();
private static final ConcurrentHashMap<String, MmsDownloadReceiver> mMap = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, MmsDownloadReceiver> mMap = new ConcurrentHashMap<>();
@@ -43,16 +44,12 @@ public class DownloadManager {
} }
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void downloadMultimediaMessage(final Context context, final String location, Uri uri, boolean byPush, int subscriptionId) { public void downloadMultimediaMessage(final Context context, final String location, Uri uri, boolean byPush, int subscriptionId) {
if (location == null || mMap.get(location) != null) { if (location == null || mMap.get(location) != null) {
return; return;
} }
// TransactionService can keep uri and location in memory while SmsManager download Mms.
if (!isNotificationExist(context, location)) {
return;
}
MmsDownloadReceiver receiver = new MmsDownloadReceiver(); MmsDownloadReceiver receiver = new MmsDownloadReceiver();
mMap.put(location, receiver); mMap.put(location, receiver);
@@ -60,7 +57,7 @@ public class DownloadManager {
context.getApplicationContext().registerReceiver(receiver, new IntentFilter(receiver.mAction)); context.getApplicationContext().registerReceiver(receiver, new IntentFilter(receiver.mAction));
Timber.v("receiving with system method"); Timber.v("receiving with system method");
final String fileName = "download." + String.valueOf(Math.abs(new Random().nextLong())) + ".dat"; final String fileName = "download." + Math.abs(new Random().nextLong()) + ".dat";
File mDownloadFile = new File(context.getCacheDir(), fileName); File mDownloadFile = new File(context.getCacheDir(), fileName);
Uri contentUri = (new Uri.Builder()) Uri contentUri = (new Uri.Builder())
.authority(context.getPackageName() + ".MmsFileProvider") .authority(context.getPackageName() + ".MmsFileProvider")
@@ -72,14 +69,19 @@ public class DownloadManager {
download.putExtra(MmsReceivedReceiver.EXTRA_LOCATION_URL, location); download.putExtra(MmsReceivedReceiver.EXTRA_LOCATION_URL, location);
download.putExtra(MmsReceivedReceiver.EXTRA_TRIGGER_PUSH, byPush); download.putExtra(MmsReceivedReceiver.EXTRA_TRIGGER_PUSH, byPush);
download.putExtra(MmsReceivedReceiver.EXTRA_URI, uri); download.putExtra(MmsReceivedReceiver.EXTRA_URI, uri);
download.putExtra(MmsReceivedReceiver.SUBSCRIPTION_ID, subscriptionId);
final PendingIntent pendingIntent = PendingIntent.getBroadcast( final PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, download, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); context, 0, download, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
final SmsManager smsManager = SmsManagerFactory.INSTANCE.createSmsManager(subscriptionId); final SmsManager smsManager = SmsManagerFactory.createSmsManager(subscriptionId);
Bundle configOverrides = new Bundle(); Bundle configOverrides = new Bundle();
String httpParams = MmsConfig.getHttpParams(); String httpParams = MmsConfig.getHttpParams();
if (!TextUtils.isEmpty(httpParams)) { if (!TextUtils.isEmpty(httpParams)) {
configOverrides.putString(SmsManager.MMS_CONFIG_HTTP_PARAMS, httpParams); configOverrides.putString(SmsManager.MMS_CONFIG_HTTP_PARAMS, httpParams);
} else {
// this doesn't seem to always work...
// configOverrides = smsManager.getCarrierConfigValues();
} }
grantUriPermission(context, contentUri); grantUriPermission(context, contentUri);
@@ -105,7 +107,7 @@ public class DownloadManager {
context.unregisterReceiver(this); context.unregisterReceiver(this);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MMS DownloadReceiver"); PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "smsmms:download-mms-lock");
wakeLock.acquire(60 * 1000); wakeLock.acquire(60 * 1000);
Intent newIntent = (Intent) intent.clone(); Intent newIntent = (Intent) intent.clone();
@@ -119,24 +121,4 @@ public class DownloadManager {
mMap.remove(location); mMap.remove(location);
} }
} }
private static boolean isNotificationExist(Context context, String location) {
String selection = Telephony.Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[] { location };
Cursor c = SqliteWrapper.query(
context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI, new String[] { Telephony.Mms._ID },
selection, selectionArgs, null);
if (c != null) {
try {
if (c.getCount() > 0) {
return true;
}
} finally {
c.close();
}
}
return false;
}
} }
+42 -27
View File
@@ -16,12 +16,13 @@
package com.android.mms.transaction; package com.android.mms.transaction;
import android.content.Context; import java.io.DataInputStream;
import android.net.http.AndroidHttpClient; import java.io.IOException;
import android.telephony.TelephonyManager; import java.net.SocketException;
import android.text.TextUtils; import java.net.URI;
import android.util.Config; import java.net.URISyntaxException;
import com.android.mms.MmsConfig; import java.util.Locale;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
@@ -33,16 +34,19 @@ import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.HttpProtocolParams;
import timber.log.Timber;
import java.io.DataInputStream; import android.content.Context;
import java.io.IOException; import android.net.http.AndroidHttpClient;
import java.net.SocketException; import android.telephony.TelephonyManager;
import java.net.URI; import android.text.TextUtils;
import java.net.URISyntaxException; import android.util.Config;
import java.util.Locale; import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
import com.android.mms.MmsConfig;
public class HttpUtils { public class HttpUtils {
private static final String TAG = LogTag.TRANSACTION;
private static final boolean DEBUG = false; private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV; private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
@@ -93,16 +97,19 @@ public class HttpUtils {
throw new IllegalArgumentException("URL must not be null."); throw new IllegalArgumentException("URL must not be null.");
} }
Timber.v("httpConnection: params list"); if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("\ttoken\t\t= " + token); Timber.v("httpConnection: params list");
Timber.v("\turl\t\t= " + url); Timber.v("\ttoken\t\t= " + token);
Timber.v("\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" Timber.v("\turl\t\t= " + url);
: ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Timber.v("\tmethod\t\t= "
Timber.v("\tisProxySet\t= " + isProxySet); + ((method == HTTP_POST_METHOD) ? "POST"
Timber.v("\tproxyHost\t= " + proxyHost); : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
Timber.v("\tproxyPort\t= " + proxyPort); Timber.v("\tisProxySet\t= " + isProxySet);
// TODO Print out binary data more readable. Timber.v("\tproxyHost\t= " + proxyHost);
//Timber.v("\tpdu\t\t= " + Arrays.toString(pdu)); Timber.v("\tproxyPort\t= " + proxyPort);
// TODO Print out binary data more readable.
//Timber.v("\tpdu\t\t= " + Arrays.toString(pdu));
}
AndroidHttpClient client = null; AndroidHttpClient client = null;
@@ -150,7 +157,10 @@ public class HttpUtils {
String xWapProfileTagName = MmsConfig.getUaProfTagName(); String xWapProfileTagName = MmsConfig.getUaProfTagName();
String xWapProfileUrl = MmsConfig.getUaProfUrl(); String xWapProfileUrl = MmsConfig.getUaProfUrl();
if (xWapProfileUrl != null) { if (xWapProfileUrl != null) {
Timber.d("[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.d(LogTag.TRANSACTION,
"[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
}
req.addHeader(xWapProfileTagName, xWapProfileUrl); req.addHeader(xWapProfileTagName, xWapProfileUrl);
} }
} }
@@ -224,7 +234,8 @@ public class HttpUtils {
bytesRead = dis.read(tempBody, offset, bytesTobeRead); bytesRead = dis.read(tempBody, offset, bytesTobeRead);
} catch (IOException e) { } catch (IOException e) {
readError = true; readError = true;
Timber.e("httpConnection: error reading input stream" + e.getMessage()); Timber.e("httpConnection: error reading input stream"
+ e.getMessage());
break; break;
} }
if (bytesRead > 0) { if (bytesRead > 0) {
@@ -237,7 +248,8 @@ public class HttpUtils {
// bytesRead will be -1 if the data was read till the eof // bytesRead will be -1 if the data was read till the eof
body = new byte[offset]; body = new byte[offset];
System.arraycopy(tempBody, 0, body, 0, offset); System.arraycopy(tempBody, 0, body, 0, offset);
Timber.v("httpConnection: Chunked response length [" + Integer.toString(offset) + "]"); Timber.v("httpConnection: Chunked response length ["
+ Integer.toString(offset) + "]");
} else { } else {
Timber.e("httpConnection: Response entity too large or empty"); Timber.e("httpConnection: Response entity too large or empty");
} }
@@ -293,7 +305,10 @@ public class HttpUtils {
// set the socket timeout // set the socket timeout
int soTimeout = MmsConfig.getHttpSocketTimeout(); int soTimeout = MmsConfig.getHttpSocketTimeout();
Timber.d("[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, " + ", UA=" + userAgent); if (Timber_isLoggable(LogTag.TRANSACTION, Log.DEBUG)) {
Timber.d("[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, "
+ ", UA=" + userAgent);
}
HttpConnectionParams.setSoTimeout(params, soTimeout); HttpConnectionParams.setSoTimeout(params, soTimeout);
return client; return client;
} }
@@ -0,0 +1,33 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.transaction;
import com.google.android.mms.MmsException;
public interface MessageSender {
public static final String RECIPIENTS_SEPARATOR = ";";
/**
* Send the message through MMS or SMS protocol.
* @param token The token to identify the sending progress.
*
* @return True if the message was sent through MMS or false if it was
* sent through SMS.
* @throws com.google.android.mms.MmsException Error occurred while sending the message.
*/
boolean sendMessage(long token) throws MmsException;
}
@@ -27,7 +27,9 @@ import android.net.Uri;
import android.provider.Telephony.Sms; import android.provider.Telephony.Sms;
import android.provider.Telephony.Sms.Inbox; import android.provider.Telephony.Sms.Inbox;
import android.telephony.SmsMessage; import android.telephony.SmsMessage;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
/** /**
* Service that gets started by the MessageStatusReceiver when a message status report is * Service that gets started by the MessageStatusReceiver when a message status report is
@@ -35,6 +37,7 @@ import timber.log.Timber;
*/ */
public class MessageStatusService extends IntentService { public class MessageStatusService extends IntentService {
private static final String[] ID_PROJECTION = new String[] { Sms._ID }; private static final String[] ID_PROJECTION = new String[] { Sms._ID };
private static final String LOG_TAG = LogTag.TAG;
private static final Uri STATUS_URI = Uri.parse("content://sms/status"); private static final Uri STATUS_URI = Uri.parse("content://sms/status");
public MessageStatusService() { public MessageStatusService() {
@@ -86,8 +89,10 @@ public class MessageStatusService extends IntentService {
boolean isStatusReport = message.isStatusReportMessage(); boolean isStatusReport = message.isStatusReportMessage();
ContentValues contentValues = new ContentValues(2); ContentValues contentValues = new ContentValues(2);
log("updateMessageStatus: msgUrl=" + messageUri + ", status=" + status if (Timber_isLoggable(LogTag.TAG, Log.DEBUG)) {
+ ", isStatusReport=" + isStatusReport); log("updateMessageStatus: msgUrl=" + messageUri + ", status=" + status +
", isStatusReport=" + isStatusReport);
}
contentValues.put(Sms.STATUS, status); contentValues.put(Sms.STATUS, status);
contentValues.put(Inbox.DATE_SENT, System.currentTimeMillis()); contentValues.put(Inbox.DATE_SENT, System.currentTimeMillis());
@@ -103,10 +108,10 @@ public class MessageStatusService extends IntentService {
} }
private void error(String message) { private void error(String message) {
Timber.e("[MessageStatusReceiver] " + message); Log.e(LOG_TAG, "[MessageStatusReceiver] " + message);
} }
private void log(String message) { private void log(String message) {
Timber.d("[MessageStatusReceiver] " + message); Log.d(LOG_TAG, "[MessageStatusReceiver] " + message);
} }
} }
@@ -0,0 +1,189 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.transaction;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.InvalidHeaderValueException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadRecInd;
import com.google.android.mms.pdu_alt.SendReq;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.send_message.Settings;
public class MmsMessageSender implements MessageSender {
private static final String TAG = LogTag.TAG;
private final Context mContext;
private final Uri mMessageUri;
private final long mMessageSize;
// Default preference values
private static final boolean DEFAULT_DELIVERY_REPORT_MODE = false;
private static final boolean DEFAULT_READ_REPORT_MODE = false;
private static final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
private static final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private static final String DEFAULT_MESSAGE_CLASS = PduHeaders.MESSAGE_CLASS_PERSONAL_STR;
private static final String DELIVERY_REPORT_PREFERENCE = "delivery_reports";
private static final String READ_REPORT_PREFERENCE = "read_reports";
public MmsMessageSender(Context context, Uri location, long messageSize) {
mContext = context;
mMessageUri = location;
mMessageSize = messageSize;
if (mMessageUri == null) {
throw new IllegalArgumentException("Null message URI.");
}
}
public boolean sendMessage(long token) throws MmsException {
// Load the MMS from the message uri
if (Timber_isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("sendMessage uri: " + mMessageUri);
}
PduPersister p = PduPersister.getPduPersister(mContext);
GenericPdu pdu = p.load(mMessageUri);
if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_SEND_REQ) {
throw new MmsException("Invalid message: " + pdu.getMessageType());
}
SendReq sendReq = (SendReq) pdu;
// Update headers.
updatePreferencesHeaders(sendReq);
// MessageClass.
sendReq.setMessageClass(DEFAULT_MESSAGE_CLASS.getBytes());
// Update the 'date' field of the message before sending it.
sendReq.setDate(System.currentTimeMillis() / 1000L);
sendReq.setMessageSize(mMessageSize);
p.updateHeaders(mMessageUri, sendReq);
long messageId = ContentUris.parseId(mMessageUri);
// Move the message into MMS Outbox.
if (!mMessageUri.toString().startsWith(Mms.Draft.CONTENT_URI.toString())) {
// If the message is already in the outbox (most likely because we created a "primed"
// message in the outbox when the user hit send), then we have to manually put an
// entry in the pending_msgs table which is where TransacationService looks for
// messages to send. Normally, the entry in pending_msgs is created by the trigger:
// insert_mms_pending_on_update, when a message is moved from drafts to the outbox.
ContentValues values = new ContentValues(7);
values.put(PendingMessages.PROTO_TYPE, MmsSms.MMS_PROTO);
values.put(PendingMessages.MSG_ID, messageId);
values.put(PendingMessages.MSG_TYPE, pdu.getMessageType());
values.put(PendingMessages.ERROR_TYPE, 0);
values.put(PendingMessages.ERROR_CODE, 0);
values.put(PendingMessages.RETRY_INDEX, 0);
values.put(PendingMessages.DUE_TIME, 0);
SqliteWrapper.insert(mContext, mContext.getContentResolver(),
PendingMessages.CONTENT_URI, values);
} else {
p.move(mMessageUri, Mms.Outbox.CONTENT_URI);
}
// Start MMS transaction service
try {
SendingProgressTokenManager.put(messageId, token);
mContext.startService(new Intent(mContext, TransactionService.class));
} catch (Exception e) {
throw new MmsException("transaction service not registered in manifest");
}
return true;
}
// Update the headers which are stored in SharedPreferences.
private void updatePreferencesHeaders(SendReq sendReq) throws MmsException {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
// Expiry.
sendReq.setExpiry(DEFAULT_EXPIRY_TIME);
// Priority.
sendReq.setPriority(DEFAULT_PRIORITY);
// Delivery report.
boolean dr = prefs.getBoolean(DELIVERY_REPORT_PREFERENCE,
DEFAULT_DELIVERY_REPORT_MODE);
sendReq.setDeliveryReport(dr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO);
// Read report.
boolean rr = prefs.getBoolean(READ_REPORT_PREFERENCE,
// default to delivery report value if read report not available
prefs.getBoolean(DELIVERY_REPORT_PREFERENCE,
DEFAULT_READ_REPORT_MODE));
sendReq.setReadReport(rr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO);
}
public static void sendReadRec(Context context, String to, String messageId, int status) {
EncodedStringValue[] sender = new EncodedStringValue[1];
sender[0] = new EncodedStringValue(to);
try {
final ReadRecInd readRec = new ReadRecInd(
new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()),
messageId.getBytes(),
PduHeaders.CURRENT_MMS_VERSION,
status,
sender);
readRec.setDate(System.currentTimeMillis() / 1000);
boolean group;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
PduPersister.getPduPersister(context).persist(readRec, Mms.Outbox.CONTENT_URI, true,
group, null, subId);
context.startService(new Intent(context, TransactionService.class));
} catch (InvalidHeaderValueException e) {
Timber.e("Invalide header value", e);
} catch (MmsException e) {
Timber.e("Persist message failed", e);
}
}
}
@@ -15,10 +15,12 @@
*/ */
package com.android.mms.transaction; package com.android.mms.transaction;
import com.android.mms.logs.LogTag;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import timber.log.Timber; import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
/** /**
* MmsPushOutboxMessages listens for MMS_SEND_OUTBOX_MSG intent . * MmsPushOutboxMessages listens for MMS_SEND_OUTBOX_MSG intent .
@@ -29,13 +31,16 @@ import timber.log.Timber;
*/ */
public class MmsPushOutboxMessages extends BroadcastReceiver { public class MmsPushOutboxMessages extends BroadcastReceiver {
private static final String INTENT_MMS_SEND_OUTBOX_MSG = "android.intent.action.MMS_SEND_OUTBOX_MSG"; private static final String INTENT_MMS_SEND_OUTBOX_MSG = "android.intent.action.MMS_SEND_OUTBOX_MSG";
private static final String TAG = LogTag.TAG;
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
Timber.v("Received the MMS_SEND_OUTBOX_MSG intent: " + intent); if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Received the MMS_SEND_OUTBOX_MSG intent: " + intent);
}
String action = intent.getAction(); String action = intent.getAction();
if(action.equalsIgnoreCase(INTENT_MMS_SEND_OUTBOX_MSG)){ if(action.equalsIgnoreCase(INTENT_MMS_SEND_OUTBOX_MSG)){
Timber.d("Now waking up the MMS service"); Log.d(TAG,"Now waking up the MMS service");
context.startService(new Intent(context, TransactionService.class)); context.startService(new Intent(context, TransactionService.class));
} }
} }
@@ -22,9 +22,12 @@ import android.content.Intent;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import android.provider.Telephony.Mms; import android.provider.Telephony.Mms;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
import com.klinker.android.send_message.Utils; import com.klinker.android.send_message.Utils;
import timber.log.Timber;
/** /**
* MmsSystemEventReceiver receives the * MmsSystemEventReceiver receives the
@@ -36,14 +39,24 @@ import timber.log.Timber;
* </ul> * </ul>
*/ */
public class MmsSystemEventReceiver extends BroadcastReceiver { public class MmsSystemEventReceiver extends BroadcastReceiver {
private static final String TAG = LogTag.TAG;
private static ConnectivityManager mConnMgr = null; private static ConnectivityManager mConnMgr = null;
public static void wakeUpService(Context context) { public static void wakeUpService(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("wakeUpService: start transaction service ...");
}
context.startService(new Intent(context, TransactionService.class));
}
} }
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
Timber.v("Intent received: " + intent); if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Intent received: " + intent);
}
if (!Utils.isDefaultSmsApp(context)) { if (!Utils.isDefaultSmsApp(context)) {
Timber.v("not default sms app, cancelling"); Timber.v("not default sms app, cancelling");
@@ -72,14 +85,18 @@ public class MmsSystemEventReceiver extends BroadcastReceiver {
//Utils.setMobileDataEnabled(context, true); //Utils.setMobileDataEnabled(context, true);
return; return;
} }
NetworkInfo mmsNetworkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS); NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
if (mmsNetworkInfo == null) { if (mmsNetworkInfo == null) {
return; return;
} }
boolean available = mmsNetworkInfo.isAvailable(); boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected(); boolean isConnected = mmsNetworkInfo.isConnected();
Timber.v("TYPE_MOBILE_MMS available = " + available + ", isConnected = " + isConnected); if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected. // Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) { if (available && !isConnected) {
@@ -29,6 +29,7 @@ import android.provider.Telephony.Mms.Inbox;
import android.provider.Telephony.Threads; import android.provider.Telephony.Threads;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import com.android.mms.logs.LogTag;
import com.android.mms.MmsConfig; import com.android.mms.MmsConfig;
import com.android.mms.util.DownloadManager; import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException; import com.google.android.mms.MmsException;
@@ -40,12 +41,13 @@ import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser; import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister; import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf; import com.google.android.mms.pdu_alt.RetrieveConf;
import timber.log.Timber;
import com.klinker.android.send_message.BroadcastUtils; import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Settings;
import java.io.IOException; import java.io.IOException;
import timber.log.Timber;
import static com.android.mms.transaction.TransactionState.FAILED; import static com.android.mms.transaction.TransactionState.FAILED;
import static com.android.mms.transaction.TransactionState.INITIALIZED; import static com.android.mms.transaction.TransactionState.INITIALIZED;
import static com.android.mms.transaction.TransactionState.SUCCESS; import static com.android.mms.transaction.TransactionState.SUCCESS;
@@ -71,6 +73,8 @@ import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_UNRECOGNIZED;
* in case the client is in immediate retrieve mode. * in case the client is in immediate retrieve mode.
*/ */
public class NotificationTransaction extends Transaction implements Runnable { public class NotificationTransaction extends Transaction implements Runnable {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGV = false;
private Uri mUri; private Uri mUri;
@@ -88,7 +92,7 @@ public class NotificationTransaction extends Transaction implements Runnable {
mNotificationInd = (NotificationInd) mNotificationInd = (NotificationInd)
PduPersister.getPduPersister(context).load(mUri); PduPersister.getPduPersister(context).load(mUri);
} catch (MmsException e) { } catch (MmsException e) {
Timber.e(e, "Failed to load NotificationInd from: " + uriString); Timber.e("Failed to load NotificationInd from: " + uriString, e);
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
@@ -110,10 +114,20 @@ public class NotificationTransaction extends Transaction implements Runnable {
try { try {
// Save the pdu. If we can start downloading the real pdu immediately, don't allow // Save the pdu. If we can start downloading the real pdu immediately, don't allow
// persist() to create a thread for the notificationInd because it causes UI jank. // persist() to create a thread for the notificationInd because it causes UI jank.
mUri = PduPersister.getPduPersister(context).persist(ind, Inbox.CONTENT_URI, boolean group;
PduPersister.DUMMY_THREAD_ID, !allowAutoDownload(mContext), true, null); int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
mUri = PduPersister.getPduPersister(context).persist(
ind, Inbox.CONTENT_URI, !allowAutoDownload(mContext),
group, null, subId);
} catch (MmsException e) { } catch (MmsException e) {
Timber.e(e, "Failed to save NotificationInd in constructor."); Timber.e("Failed to save NotificationInd in constructor.", e);
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
@@ -184,18 +198,20 @@ public class NotificationTransaction extends Transaction implements Runnable {
} else { } else {
// Save the received PDU (must be a M-RETRIEVE.CONF). // Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext); PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI, PduPersister.DUMMY_THREAD_ID, Uri uri = p.persist(pdu, Inbox.CONTENT_URI, true,
true, true, null); com.klinker.android.send_message.Transaction.settings.getGroup(), null, com.klinker.android.send_message.Transaction.settings.getSubscriptionId());
RetrieveConf retrieveConf = (RetrieveConf) pdu;
// Use local time instead of PDU time // Use local time instead of PDU time
ContentValues values = new ContentValues(2); ContentValues values = new ContentValues(2);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L); values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
try { try {
// Store PDU time as sent time for received message
RetrieveConf retrieveConf = (RetrieveConf) pdu;
values.put(Mms.DATE_SENT, retrieveConf.getDate()); values.put(Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) { } catch (Exception e) {
} }
SqliteWrapper.update(mContext, mContext.getContentResolver(), SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null); uri, values, null, null);
@@ -237,7 +253,7 @@ public class NotificationTransaction extends Transaction implements Runnable {
sendNotifyRespInd(status); sendNotifyRespInd(status);
} catch (Throwable t) { } catch (Throwable t) {
Timber.e(t, "error"); Timber.e("error", t);
} finally { } finally {
mTransactionState.setContentUri(mUri); mTransactionState.setContentUri(mUri);
if (!autoDownload) { if (!autoDownload) {
View File

Some files were not shown because too many files have changed in this diff Show More