[automerger skipped] Use public sendOrderedBroadcast am: c4c3b281c1 am: 0f38ae3332
am: ed1c035de8 -s ours
am skip reason: change_id Ia29228a5acc40c0ff1e3df1b3b3d9d193d304320 with SHA1 6e11dca8df is in history
Change-Id: Icf5a163dbcf2ddcc7de0704fe24718cdc5d2d1aa
diff --git a/Android.bp b/Android.bp
index c72b5c8..68fd40b 100644
--- a/Android.bp
+++ b/Android.bp
@@ -1,7 +1,7 @@
// Copyright 2019 The Android Open Source Project
-
-android_app {
- name: "CellBroadcastServiceModule",
+java_defaults {
+ name: "CellBroadcastServiceCommon",
+ min_sdk_version: "29",
srcs: [
"src/**/*.java",
":framework-annotations",
@@ -15,6 +15,25 @@
optimize: {
proguard_flags_files: ["proguard.flags"],
},
+ jarjar_rules: "cellbroadcast-jarjar-rules.txt",
+ plugins: ["java_api_finder"],
+}
+
+android_app {
+ name: "CellBroadcastServiceModule",
+ defaults: ["CellBroadcastServiceCommon"],
+ certificate: "networkstack",
+ manifest: "AndroidManifest.xml",
+}
+
+android_app {
+ name: "CellBroadcastServiceModulePlatform",
+ defaults: ["CellBroadcastServiceCommon"],
+ certificate: "platform",
+ // CellBroadcastServicePlatformModule is a replacement for com.android.cellbroadcast apex
+ // which consists of CellBroadcastServiceModule
+ overrides: ["com.android.cellbroadcast"],
+ manifest: "AndroidManifest_Platform.xml",
}
// used to share common constants between cellbroadcastservice and cellbroadcastreceier
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 4dc0b97..bd76af1 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -17,7 +17,9 @@
*/
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- android:sharedUserId="android.uid.phone"
+ android:sharedUserId="android.uid.networkstack"
+ android:versionCode="300000000"
+ android:versionName="R-initial"
package="com.android.cellbroadcastservice">
<original-package android:name="com.android.cellbroadcastservice" />
@@ -29,15 +31,19 @@
<uses-permission android:name="android.permission.READ_CELL_BROADCASTS" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
+ <uses-permission android:name="android.permission.BROADCAST_SMS" />
+ <uses-permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS" />
<uses-sdk android:minSdkVersion="29"/>
<application android:label="Module used to handle cell broadcasts."
android:defaultToDeviceProtectedStorage="true"
android:directBootAware="true"
- android:process="com.android.phone">
+ android:persistent="true"
+ android:process="com.android.networkstack.process">
<service android:name="DefaultCellBroadcastService"
+ android:process="com.android.networkstack.process"
android:exported="true"
android:permission="android.permission.BIND_CELL_BROADCAST_SERVICE">
<intent-filter>
diff --git a/AndroidManifest_Platform.xml b/AndroidManifest_Platform.xml
new file mode 100644
index 0000000..067741f
--- /dev/null
+++ b/AndroidManifest_Platform.xml
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+ * Copyright (C) 2019 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.
+ */
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ android:sharedUserId="android.uid.phone"
+ package="com.android.cellbroadcastservice">
+
+ <original-package android:name="com.android.cellbroadcastservice" />
+
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.RECEIVE_SMS" />
+ <uses-permission android:name="android.permission.RECEIVE_EMERGENCY_BROADCAST" />
+ <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
+ <uses-permission android:name="android.permission.READ_CELL_BROADCASTS" />
+ <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+ <uses-permission android:name="android.permission.BROADCAST_SMS" />
+ <uses-permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS" />
+
+ <uses-sdk android:minSdkVersion="29"/>
+
+ <application android:label="Module used to handle cell broadcasts."
+ android:defaultToDeviceProtectedStorage="true"
+ android:persistent="true"
+ android:directBootAware="true"
+ android:process="com.android.phone">
+
+ <service android:name="DefaultCellBroadcastService"
+ android:process="com.android.phone"
+ android:exported="true"
+ android:permission="android.permission.BIND_CELL_BROADCAST_SERVICE">
+ <intent-filter>
+ <action android:name="android.telephony.CellBroadcastService" />
+ </intent-filter>
+ </service>
+ </application>
+</manifest>
diff --git a/CleanSpec.mk b/CleanSpec.mk
new file mode 100644
index 0000000..f69421d
--- /dev/null
+++ b/CleanSpec.mk
@@ -0,0 +1,50 @@
+# 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.
+#
+
+# If you don't need to do a full clean build but would like to touch
+# a file or delete some intermediate files, add a clean step to the end
+# of the list. These steps will only be run once, if they haven't been
+# run before.
+#
+# E.g.:
+# $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
+# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
+#
+# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
+# files that are missing or have been moved.
+#
+# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
+# Use $(OUT_DIR) to refer to the "out" directory.
+#
+# If you need to re-do something that's already mentioned, just copy
+# the command and add it to the bottom of the list. E.g., if a change
+# that you made last week required touching a file and a change you
+# made today requires touching the same file, just copy the old
+# touch step and add it to the end of the list.
+#
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
+
+# For example:
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
+#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
+#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
+
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/priv-app/CellBroadcastServiceModule)
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
diff --git a/cellbroadcast-jarjar-rules.txt b/cellbroadcast-jarjar-rules.txt
index b50ec50..3e4127a 100644
--- a/cellbroadcast-jarjar-rules.txt
+++ b/cellbroadcast-jarjar-rules.txt
@@ -1,4 +1,6 @@
-rule android.util.LocalLog* com.android.cellbroadcast.LocalLog@1
-rule android.util.Slog* com.android.cellbroadcast.Slog@1
-rule com.android.internal.util.State* com.android.cellbroadcastservice.State@1
-rule com.android.internal.util.StateMachine* com.android.cellbroadcastservice.StateMachine@1
+rule android.os.HandlerExecutor* com.android.cellbroadcastservice.HandlerExecutor@1
+rule android.util.LocalLog* com.android.cellbroadcastservice.LocalLog@1
+rule android.internal.util.IState* com.android.cellbroadcastservice.IState@1
+rule android.internal.util.Preconditions* com.android.cellbroadcastservice.Preconditions@1
+rule android.internal.util.State* com.android.cellbroadcastservice.State@1
+rule android.internal.util.StateMachine* com.android.cellbroadcastservice.StateMachine@1
diff --git a/src/com/android/cellbroadcastservice/BearerData.java b/src/com/android/cellbroadcastservice/BearerData.java
index cc7a155..d73339c 100644
--- a/src/com/android/cellbroadcastservice/BearerData.java
+++ b/src/com/android/cellbroadcastservice/BearerData.java
@@ -17,9 +17,9 @@
package com.android.cellbroadcastservice;
import android.content.Context;
+import android.telephony.Rlog;
import android.telephony.SmsCbCmasInfo;
import android.telephony.cdma.CdmaSmsCbProgramData;
-import android.util.Log;
/**
* An object to decode CDMA SMS bearer data.
@@ -194,9 +194,9 @@
inStream.skip(3);
}
if ((!decodeSuccess) || (paramBits > 0)) {
- Log.d(LOG_TAG, "MESSAGE_IDENTIFIER decode " +
- (decodeSuccess ? "succeeded" : "failed") +
- " (extra bits = " + paramBits + ")");
+ Rlog.d(LOG_TAG, "MESSAGE_IDENTIFIER decode "
+ + (decodeSuccess ? "succeeded" : "failed")
+ + " (extra bits = " + paramBits + ")");
}
inStream.skip(paramBits);
return decodeSuccess;
@@ -211,7 +211,7 @@
decodeSuccess = true;
inStream.skip(paramBits);
}
- Log.d(LOG_TAG, "RESERVED bearer data subparameter " + subparamId + " decode "
+ Rlog.d(LOG_TAG, "RESERVED bearer data subparameter " + subparamId + " decode "
+ (decodeSuccess ? "succeeded" : "failed") + " (param bits = " + paramBits + ")");
if (!decodeSuccess) {
throw new CodingException("RESERVED bearer data subparameter " + subparamId
@@ -263,7 +263,7 @@
if (maxNumFields < 0) {
throw new CodingException(charset + " decode failed: offset out of range");
}
- Log.e(LOG_TAG, charset + " decode error: offset = " + offset + " numFields = "
+ Rlog.e(LOG_TAG, charset + " decode error: offset = " + offset + " numFields = "
+ numFields + " data.length = " + data.length + " maxNumFields = "
+ maxNumFields);
numFields = maxNumFields;
@@ -432,9 +432,9 @@
bData.language = inStream.read(8);
}
if ((!decodeSuccess) || (paramBits > 0)) {
- Log.d(LOG_TAG, "LANGUAGE_INDICATOR decode " +
- (decodeSuccess ? "succeeded" : "failed") +
- " (extra bits = " + paramBits + ")");
+ Rlog.d(LOG_TAG, "LANGUAGE_INDICATOR decode "
+ + (decodeSuccess ? "succeeded" : "failed")
+ + " (extra bits = " + paramBits + ")");
}
inStream.skip(paramBits);
return decodeSuccess;
@@ -452,9 +452,9 @@
inStream.skip(6);
}
if ((!decodeSuccess) || (paramBits > 0)) {
- Log.d(LOG_TAG, "PRIORITY_INDICATOR decode " +
- (decodeSuccess ? "succeeded" : "failed") +
- " (extra bits = " + paramBits + ")");
+ Rlog.d(LOG_TAG, "PRIORITY_INDICATOR decode "
+ + (decodeSuccess ? "succeeded" : "failed")
+ + " (extra bits = " + paramBits + ")");
}
inStream.skip(paramBits);
return decodeSuccess;
@@ -553,7 +553,7 @@
break;
default:
- Log.w(LOG_TAG, "skipping unsupported CMAS record type " + recordType);
+ Rlog.w(LOG_TAG, "skipping unsupported CMAS record type " + recordType);
inStream.skip(recordLen * 8);
break;
}
@@ -631,9 +631,9 @@
}
return bData;
} catch (BitwiseInputStream.AccessException ex) {
- Log.e(LOG_TAG, "BearerData decode failed: " + ex);
+ Rlog.e(LOG_TAG, "BearerData decode failed: " + ex);
} catch (CodingException ex) {
- Log.e(LOG_TAG, "BearerData decode failed: " + ex);
+ Rlog.e(LOG_TAG, "BearerData decode failed: " + ex);
}
return null;
}
diff --git a/src/com/android/cellbroadcastservice/CbGeoUtils.java b/src/com/android/cellbroadcastservice/CbGeoUtils.java
index 0a8fe48..2a7a1d7 100644
--- a/src/com/android/cellbroadcastservice/CbGeoUtils.java
+++ b/src/com/android/cellbroadcastservice/CbGeoUtils.java
@@ -19,8 +19,8 @@
import android.annotation.NonNull;
import android.telephony.CbGeoUtils.Geometry;
import android.telephony.CbGeoUtils.LatLng;
+import android.telephony.Rlog;
import android.text.TextUtils;
-import android.util.Log;
import java.util.ArrayList;
import java.util.List;
@@ -231,7 +231,7 @@
geometries.add(new Polygon(vertices));
break;
default:
- Log.e(TAG, "Invalid geometry format " + geometryStr);
+ Rlog.e(TAG, "Invalid geometry format " + geometryStr);
}
}
return geometries;
@@ -284,7 +284,7 @@
sb.append("|");
sb.append(circle.getRadius());
} else {
- Log.e(TAG, "Unsupported geometry object " + geometry);
+ Rlog.e(TAG, "Unsupported geometry object " + geometry);
return null;
}
return sb.toString();
diff --git a/src/com/android/cellbroadcastservice/CdmaServiceCategoryProgramHandler.java b/src/com/android/cellbroadcastservice/CdmaServiceCategoryProgramHandler.java
index 4b73258..032edcc 100644
--- a/src/com/android/cellbroadcastservice/CdmaServiceCategoryProgramHandler.java
+++ b/src/com/android/cellbroadcastservice/CdmaServiceCategoryProgramHandler.java
@@ -26,7 +26,6 @@
import android.os.Looper;
import android.os.Message;
import android.provider.Telephony.Sms.Intents;
-import android.telephony.SubscriptionManager;
import android.telephony.cdma.CdmaSmsCbProgramData;
import java.util.ArrayList;
@@ -135,7 +134,7 @@
Intent intent = new Intent(Intents.SMS_SERVICE_CATEGORY_PROGRAM_DATA_RECEIVED_ACTION);
intent.putExtra("sender", originatingAddress);
intent.putParcelableArrayListExtra("program_data", programData);
- SubscriptionManager.putPhoneIdAndSubIdExtra(intent, phoneId);
+ CellBroadcastHandler.putPhoneIdAndSubIdExtra(mContext, intent, phoneId);
// TODO: move this resource and its overlays to the CellBroadcastService directory
String[] pkgs = mContext.getResources().getStringArray(
diff --git a/src/com/android/cellbroadcastservice/CellBroadcastHandler.java b/src/com/android/cellbroadcastservice/CellBroadcastHandler.java
index 2c7a9e6..28e56b5 100644
--- a/src/com/android/cellbroadcastservice/CellBroadcastHandler.java
+++ b/src/com/android/cellbroadcastservice/CellBroadcastHandler.java
@@ -16,6 +16,9 @@
package com.android.cellbroadcastservice;
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+
import android.Manifest;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -30,11 +33,12 @@
import android.content.res.Resources;
import android.database.Cursor;
import android.location.Location;
-import android.location.LocationListener;
import android.location.LocationManager;
+import android.location.LocationRequest;
import android.net.Uri;
-import android.os.Bundle;
+import android.os.CancellationSignal;
import android.os.Handler;
+import android.os.HandlerExecutor;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
@@ -45,13 +49,13 @@
import android.provider.Telephony.CellBroadcasts;
import android.telephony.CbGeoUtils.Geometry;
import android.telephony.CbGeoUtils.LatLng;
+import android.telephony.CellBroadcastIntents;
+import android.telephony.Rlog;
import android.telephony.SmsCbMessage;
import android.telephony.SubscriptionManager;
import android.telephony.cdma.CdmaSmsCbProgramData;
import android.text.TextUtils;
-import android.text.format.DateUtils;
import android.util.LocalLog;
-import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -64,6 +68,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -96,7 +101,7 @@
private static final boolean IS_DEBUGGABLE = SystemProperties.getInt("ro.debuggable", 0) == 1;
/** Uses to request the location update. */
- public final LocationRequester mLocationRequester;
+ private final LocationRequester mLocationRequester;
/** Timestamp of last airplane mode on */
protected long mLastAirplaneModeTime = 0;
@@ -123,7 +128,7 @@
mLocationRequester = new LocationRequester(
context,
(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE),
- getHandler().getLooper());
+ getHandler());
// Adding GSM / CDMA service category mapping.
mServiceCategoryCrossRATMap = Stream.of(new Integer[][] {
@@ -346,7 +351,6 @@
// Check serial number if message is from the same carrier.
if (message.getSerialNumber() != messageToCheck.getSerialNumber()) {
// Not a dup. Check next one.
- log("Serial number check. Not a dup. " + messageToCheck);
continue;
}
@@ -355,7 +359,6 @@
&& message.getEtwsWarningInfo().isPrimary()
!= messageToCheck.getEtwsWarningInfo().isPrimary()) {
// Not a dup. Check next one.
- log("ETWS primary check. Not a dup. " + messageToCheck);
continue;
}
@@ -369,7 +372,6 @@
messageToCheck.getServiceCategory()),
message.getServiceCategory())) {
// Not a dup. Check next one.
- log("Service category check. Not a dup. " + messageToCheck);
continue;
}
@@ -434,9 +436,9 @@
* @param phoneId the phoneId to use
* @return the associated sub id
*/
- protected int getSubIdForPhone(int phoneId) {
+ protected static int getSubIdForPhone(Context context, int phoneId) {
SubscriptionManager subMan =
- (SubscriptionManager) mContext.getSystemService(
+ (SubscriptionManager) context.getSystemService(
Context.TELEPHONY_SUBSCRIPTION_SERVICE);
int[] subIds = subMan.getSubscriptionIds(phoneId);
if (subIds != null) {
@@ -447,6 +449,19 @@
}
/**
+ * Put the phone ID and sub ID into an intent as extras.
+ */
+ public static void putPhoneIdAndSubIdExtra(Context context, Intent intent, int phoneId) {
+ int subId = getSubIdForPhone(context, phoneId);
+ if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+ intent.putExtra("subscription", subId);
+ intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
+ }
+ intent.putExtra("phone", phoneId);
+ intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, phoneId);
+ }
+
+ /**
* Broadcast the {@code message} to the applications.
* @param message a message need to broadcast
* @param messageUri message's uri
@@ -468,13 +483,7 @@
appOp = AppOpsManager.OPSTR_RECEIVE_EMERGENCY_BROADCAST;
intent.putExtra(EXTRA_MESSAGE, message);
- int subId = getSubIdForPhone(slotIndex);
- if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
- intent.putExtra("subscription", subId);
- intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
- }
- intent.putExtra("phone", slotIndex);
- intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, slotIndex);
+ putPhoneIdAndSubIdExtra(mContext, intent, slotIndex);
if (IS_DEBUGGABLE) {
// Send additional broadcast intent to the specified package. This is only for sl4a
@@ -509,20 +518,20 @@
msg = "Dispatching SMS CB, SmsCbMessage is: " + message;
log(msg);
mLocalLog.log(msg);
- intent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION);
// Send implicit intent since there are various 3rd party carrier apps listen to
// this intent.
- intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+ intent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION);
receiverPermission = Manifest.permission.RECEIVE_SMS;
appOp = AppOpsManager.OPSTR_RECEIVE_SMS;
intent.putExtra(EXTRA_MESSAGE, message);
- SubscriptionManager.putPhoneIdAndSubIdExtra(intent, slotIndex);
+ putPhoneIdAndSubIdExtra(mContext, intent, slotIndex);
mReceiverCount.incrementAndGet();
- mContext.createContextAsUser(UserHandle.ALL, 0).sendOrderedBroadcast(
- intent, receiverPermission, appOp, mReceiver, getHandler(),
- Activity.RESULT_OK, null, null);
+ CellBroadcastIntents.sendOrderedBroadcastForBackgroundReceivers(
+ mContext, UserHandle.ALL, intent,
+ receiverPermission, appOp, mReceiver, getHandler(), Activity.RESULT_OK,
+ null, null);
}
if (messageUri != null) {
@@ -578,18 +587,9 @@
/**
* Use as the default maximum wait time if the cell broadcast doesn't specify the value.
- * Most of the location request should be responded within 20 seconds.
+ * Most of the location request should be responded within 30 seconds.
*/
- private static final int DEFAULT_MAXIMUM_WAIT_TIME_SEC = 20;
-
- /**
- * Trigger this event when the {@link LocationManager} is not responded within the given
- * time.
- */
- private static final int EVENT_LOCATION_REQUEST_TIMEOUT = 1;
-
- /** Request a single location update. */
- private static final int EVENT_REQUEST_LOCATION_UPDATE = 2;
+ private static final int DEFAULT_MAXIMUM_WAIT_TIME_SEC = 30;
/**
* Request location update from network or gps location provider. Network provider will be
@@ -599,17 +599,20 @@
LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER);
private final LocationManager mLocationManager;
- private final Looper mLooper;
private final List<LocationUpdateCallback> mCallbacks;
private final Context mContext;
- private Handler mLocationHandler;
+ private final Handler mLocationHandler;
- LocationRequester(Context context, LocationManager locationManager, Looper looper) {
+ private int mNumLocationUpdatesInProgress;
+
+ private final List<CancellationSignal> mCancellationSignals = new ArrayList<>();
+
+ LocationRequester(Context context, LocationManager locationManager, Handler handler) {
mLocationManager = locationManager;
- mLooper = looper;
mCallbacks = new ArrayList<>();
mContext = context;
- mLocationHandler = new LocationHandler(looper);
+ mLocationHandler = handler;
+ mNumLocationUpdatesInProgress = 0;
}
/**
@@ -617,103 +620,83 @@
* {@code null} location will be called immediately.
*
* @param callback a callback to the response when the location is available
- * @param maximumWaitTimeSec the maximum wait time of this request. If location is not
+ * @param maximumWaitTimeS the maximum wait time of this request. If location is not
* updated within the maximum wait time, {@code callback#onLocationUpadte(null)} will be
* called.
*/
void requestLocationUpdate(@NonNull LocationUpdateCallback callback,
- int maximumWaitTimeSec) {
- mLocationHandler.obtainMessage(EVENT_REQUEST_LOCATION_UPDATE, maximumWaitTimeSec,
- 0 /* arg2 */, callback).sendToTarget();
+ int maximumWaitTimeS) {
+ mLocationHandler.post(() -> requestLocationUpdateInternal(callback, maximumWaitTimeS));
}
- private void onLocationUpdate(@Nullable LatLng location) {
+ private void onLocationUpdate(@Nullable Location location) {
+ mNumLocationUpdatesInProgress--;
+
+ LatLng latLng = null;
+ if (location != null) {
+ Rlog.d(TAG, "Got location update");
+ latLng = new LatLng(location.getLatitude(), location.getLongitude());
+ } else if (mNumLocationUpdatesInProgress > 0) {
+ Rlog.d(TAG, "Still waiting for " + mNumLocationUpdatesInProgress
+ + " more location updates.");
+ return;
+ } else {
+ Rlog.d(TAG, "Location is not available.");
+ }
+
for (LocationUpdateCallback callback : mCallbacks) {
- callback.onLocationUpdate(location);
+ callback.onLocationUpdate(latLng);
}
mCallbacks.clear();
+
+ mCancellationSignals.forEach(CancellationSignal::cancel);
+ mCancellationSignals.clear();
+
+ mNumLocationUpdatesInProgress = 0;
}
private void requestLocationUpdateInternal(@NonNull LocationUpdateCallback callback,
- int maximumWaitTimeSec) {
- if (DBG) Log.d(TAG, "requestLocationUpdate");
- if (!isLocationServiceAvailable()) {
+ int maximumWaitTimeS) {
+ if (DBG) Rlog.d(TAG, "requestLocationUpdate");
+ if (!hasPermission(ACCESS_FINE_LOCATION) && !hasPermission(ACCESS_COARSE_LOCATION)) {
if (DBG) {
- Log.d(TAG, "Can't request location update because of no location permission");
+ Rlog.d(TAG, "Can't request location update because of no location permission");
}
callback.onLocationUpdate(null);
return;
}
+ if (mNumLocationUpdatesInProgress == 0) {
+ for (String provider : LOCATION_PROVIDERS) {
+ if (!mLocationManager.isProviderEnabled(provider)) {
+ if (DBG) {
+ Rlog.d(TAG, "provider " + provider + " not available");
+ }
+ continue;
+ }
+ LocationRequest request = LocationRequest.createFromDeprecatedProvider(provider,
+ 0, 0, true);
+ if (maximumWaitTimeS == SmsCbMessage.MAXIMUM_WAIT_TIME_NOT_SET) {
+ maximumWaitTimeS = DEFAULT_MAXIMUM_WAIT_TIME_SEC;
+ }
+ request.setExpireIn(TimeUnit.SECONDS.toMillis(maximumWaitTimeS));
- if (!mLocationHandler.hasMessages(EVENT_LOCATION_REQUEST_TIMEOUT)) {
- if (maximumWaitTimeSec == SmsCbMessage.MAXIMUM_WAIT_TIME_NOT_SET) {
- maximumWaitTimeSec = DEFAULT_MAXIMUM_WAIT_TIME_SEC;
- }
- mLocationHandler.sendMessageDelayed(
- mLocationHandler.obtainMessage(EVENT_LOCATION_REQUEST_TIMEOUT),
- maximumWaitTimeSec * DateUtils.SECOND_IN_MILLIS);
- }
-
- mCallbacks.add(callback);
-
- for (String provider : LOCATION_PROVIDERS) {
- if (mLocationManager.isProviderEnabled(provider)) {
- mLocationManager.requestSingleUpdate(provider, mLocationListener, mLooper);
- break;
+ CancellationSignal signal = new CancellationSignal();
+ mCancellationSignals.add(signal);
+ mLocationManager.getCurrentLocation(request, signal,
+ new HandlerExecutor(mLocationHandler), this::onLocationUpdate);
+ mNumLocationUpdatesInProgress++;
}
}
- }
-
- private boolean isLocationServiceAvailable() {
- if (!hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)
- && !hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) return false;
- for (String provider : LOCATION_PROVIDERS) {
- if (mLocationManager.isProviderEnabled(provider)) return true;
+ if (mNumLocationUpdatesInProgress > 0) {
+ mCallbacks.add(callback);
+ } else {
+ callback.onLocationUpdate(null);
}
- return false;
}
private boolean hasPermission(String permission) {
return mContext.checkPermission(permission, Process.myPid(), Process.myUid())
== PackageManager.PERMISSION_GRANTED;
}
-
- private final LocationListener mLocationListener = new LocationListener() {
- @Override
- public void onLocationChanged(Location location) {
- mLocationHandler.removeMessages(EVENT_LOCATION_REQUEST_TIMEOUT);
- onLocationUpdate(new LatLng(location.getLatitude(), location.getLongitude()));
- }
-
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {}
-
- @Override
- public void onProviderEnabled(String provider) {}
-
- @Override
- public void onProviderDisabled(String provider) {}
- };
-
- private final class LocationHandler extends Handler {
- LocationHandler(Looper looper) {
- super(looper);
- }
-
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case EVENT_LOCATION_REQUEST_TIMEOUT:
- if (DBG) Log.d(TAG, "location request timeout");
- onLocationUpdate(null);
- break;
- case EVENT_REQUEST_LOCATION_UPDATE:
- requestLocationUpdateInternal((LocationUpdateCallback) msg.obj, msg.arg1);
- break;
- default:
- Log.e(TAG, "Unsupported message type " + msg.what);
- }
- }
- }
}
}
diff --git a/src/com/android/cellbroadcastservice/CellBroadcastProvider.java b/src/com/android/cellbroadcastservice/CellBroadcastProvider.java
index e45daca..f7dea4e 100644
--- a/src/com/android/cellbroadcastservice/CellBroadcastProvider.java
+++ b/src/com/android/cellbroadcastservice/CellBroadcastProvider.java
@@ -31,6 +31,7 @@
import android.os.Binder;
import android.os.Process;
import android.provider.Telephony.CellBroadcasts;
+import android.telephony.Rlog;
import android.text.TextUtils;
import android.util.Log;
@@ -179,7 +180,7 @@
checkReadPermission(uri);
if (DBG) {
- Log.d(TAG, "query:"
+ Rlog.d(TAG, "query:"
+ " uri = " + uri
+ " projection = " + Arrays.toString(projection)
+ " selection = " + selection
@@ -219,7 +220,7 @@
checkWritePermission();
if (DBG) {
- Log.d(TAG, "insert:"
+ Rlog.d(TAG, "insert:"
+ " uri = " + uri
+ " contentValue = " + values);
}
@@ -234,7 +235,7 @@
.notifyChange(CONTENT_URI, null /* observer */);
return newUri;
} else {
- Log.e(TAG, "Insert record failed because of unknown reason, uri = " + uri);
+ Rlog.e(TAG, "Insert record failed because of unknown reason, uri = " + uri);
return null;
}
default:
@@ -248,7 +249,7 @@
checkWritePermission();
if (DBG) {
- Log.d(TAG, "delete:"
+ Rlog.d(TAG, "delete:"
+ " uri = " + uri
+ " selection = " + selection
+ " selectionArgs = " + Arrays.toString(selectionArgs));
@@ -269,7 +270,7 @@
checkWritePermission();
if (DBG) {
- Log.d(TAG, "update:"
+ Rlog.d(TAG, "update:"
+ " uri = " + uri
+ " values = {" + values + "}"
+ " selection = " + selection
@@ -376,12 +377,12 @@
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (DBG) {
- Log.d(TAG, "onUpgrade: oldV=" + oldVersion + " newV=" + newVersion);
+ Rlog.d(TAG, "onUpgrade: oldV=" + oldVersion + " newV=" + newVersion);
}
if (oldVersion < 2) {
db.execSQL("ALTER TABLE " + CELL_BROADCASTS_TABLE_NAME + " ADD COLUMN "
+ CellBroadcasts.SLOT_INDEX + " INTEGER DEFAULT 0;");
- Log.d(TAG, "add slotIndex column");
+ Rlog.d(TAG, "add slotIndex column");
}
}
}
@@ -389,18 +390,26 @@
private class CellBroadcastPermissionChecker implements PermissionChecker {
@Override
public boolean hasWritePermission() {
- // Only the phone and network statck process has the write permission to modify this
- // provider.
- return Binder.getCallingUid() == Process.PHONE_UID
- || Binder.getCallingUid() == Process.NETWORK_STACK_UID;
+ // Only the telephony system compontents e.g, Cellbroadcast service has the write
+ // permission to modify this provider.
+ int status = getContext().checkCallingOrSelfPermission(
+ "android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS");
+ if (status == PackageManager.PERMISSION_GRANTED) {
+ return true;
+ }
+ return false;
}
@Override
public boolean hasReadPermission() {
- // Only the phone and network stack process has the read permission to query data from
- // this provider.
- return Binder.getCallingUid() == Process.PHONE_UID
- || Binder.getCallingUid() == Process.NETWORK_STACK_UID;
+ // Only the telephony system compontents e.g, Cellbroadcast service has the read
+ // permission to access this provider.
+ int status = getContext().checkCallingOrSelfPermission(
+ "android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS");
+ if (status == PackageManager.PERMISSION_GRANTED) {
+ return true;
+ }
+ return false;
}
@Override
diff --git a/src/com/android/cellbroadcastservice/DefaultCellBroadcastService.java b/src/com/android/cellbroadcastservice/DefaultCellBroadcastService.java
index 42e1e5c..340d72d 100644
--- a/src/com/android/cellbroadcastservice/DefaultCellBroadcastService.java
+++ b/src/com/android/cellbroadcastservice/DefaultCellBroadcastService.java
@@ -19,12 +19,12 @@
import android.content.Context;
import android.os.Bundle;
import android.telephony.CellBroadcastService;
+import android.telephony.Rlog;
import android.telephony.SmsCbLocation;
import android.telephony.SmsCbMessage;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaSmsCbProgramData;
-import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -59,13 +59,13 @@
@Override
public void onGsmCellBroadcastSms(int slotIndex, byte[] message) {
- Log.d(TAG, "onGsmCellBroadcastSms received message on slotId=" + slotIndex);
+ Rlog.d(TAG, "onGsmCellBroadcastSms received message on slotId=" + slotIndex);
mGsmCellBroadcastHandler.onGsmCellBroadcastSms(slotIndex, message);
}
@Override
public void onCdmaCellBroadcastSms(int slotIndex, byte[] bearerData, int serviceCategory) {
- Log.d(TAG, "onCdmaCellBroadcastSms received message on slotId=" + slotIndex);
+ Rlog.d(TAG, "onCdmaCellBroadcastSms received message on slotId=" + slotIndex);
int[] subIds =
((SubscriptionManager) getSystemService(
Context.TELEPHONY_SUBSCRIPTION_SERVICE)).getSubscriptionIds(slotIndex);
@@ -88,7 +88,7 @@
@Override
public void onCdmaScpMessage(int slotIndex, List<CdmaSmsCbProgramData> programData,
String originatingAddress, Consumer<Bundle> callback) {
- Log.d(TAG, "onCdmaScpMessage received message on slotId=" + slotIndex);
+ Rlog.d(TAG, "onCdmaScpMessage received message on slotId=" + slotIndex);
mCdmaScpHandler.onCdmaScpMessage(slotIndex, new ArrayList<>(programData),
originatingAddress, callback);
}
@@ -107,10 +107,10 @@
int serviceCategory) {
BearerData bData = BearerData.decode(context, bearerData, serviceCategory);
if (bData == null) {
- Log.w(TAG, "BearerData.decode() returned null");
+ Rlog.w(TAG, "BearerData.decode() returned null");
return null;
}
- Log.d(TAG, "MT raw BearerData = " + toHexString(bearerData, 0, bearerData.length));
+ Rlog.d(TAG, "MT raw BearerData = " + toHexString(bearerData, 0, bearerData.length));
SmsCbLocation location = new SmsCbLocation(plmn);
SubscriptionManager sm = (SubscriptionManager) context.getSystemService(
@@ -124,7 +124,8 @@
return new SmsCbMessage(SmsCbMessage.MESSAGE_FORMAT_3GPP2,
SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE, bData.messageId, location,
serviceCategory, bData.getLanguage(), bData.userData.payloadStr,
- bData.priority, null, bData.cmasWarningInfo, slotIndex, subId);
+ bData.priority, null, bData.cmasWarningInfo, 0, null, System.currentTimeMillis(),
+ slotIndex, subId);
}
private static String toHexString(byte[] array, int offset, int length) {
diff --git a/src/com/android/cellbroadcastservice/GsmAlphabet.java b/src/com/android/cellbroadcastservice/GsmAlphabet.java
index aecaf1b..9c52189 100644
--- a/src/com/android/cellbroadcastservice/GsmAlphabet.java
+++ b/src/com/android/cellbroadcastservice/GsmAlphabet.java
@@ -16,8 +16,7 @@
package com.android.cellbroadcastservice;
-import android.annotation.UnsupportedAppUsage;
-import android.util.Log;
+import android.telephony.Rlog;
import android.util.SparseIntArray;
/**
@@ -67,18 +66,15 @@
public static final int UDH_SEPTET_COST_CONCATENATED_MESSAGE = 6;
/** Reverse mapping from Unicode characters to indexes into language tables. */
- @UnsupportedAppUsage
private static SparseIntArray[] sCharsToGsmTables;
/** Reverse mapping from Unicode characters to indexes into language shift tables. */
- @UnsupportedAppUsage
private static SparseIntArray[] sCharsToShiftTables;
/**
* GSM default 7 bit alphabet plus national language locking shift character tables.
* Comment lines above strings indicate the lower four bits of the table position.
*/
- @UnsupportedAppUsage
private static final String[] sLanguageTables = {
/* 3GPP TS 23.038 V9.1.1 section 6.2.1 - GSM 7 bit Default Alphabet
01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0....
@@ -391,7 +387,6 @@
/**
* GSM default extension table plus national language single shift character tables.
*/
- @UnsupportedAppUsage
private static final String[] sLanguageShiftTables = new String[]{
/* 6.2.1.1 GSM 7 bit Default Alphabet Extension Table
0123456789A.....BCDEF0123456789ABCDEF0123456789ABCDEF
@@ -584,7 +579,7 @@
int numTables = sLanguageTables.length;
int numShiftTables = sLanguageShiftTables.length;
if (numTables != numShiftTables) {
- Log.e(TAG, "Error: language tables array length " + numTables
+ Rlog.e(TAG, "Error: language tables array length " + numTables
+ " != shift tables array length " + numShiftTables);
}
@@ -594,7 +589,7 @@
int tableLen = table.length();
if (tableLen != 0 && tableLen != 128) {
- Log.e(TAG, "Error: language tables index " + i + " length " + tableLen
+ Rlog.e(TAG, "Error: language tables index " + i + " length " + tableLen
+ " (expected 128 or 0)");
}
@@ -612,7 +607,7 @@
int shiftTableLen = shiftTable.length();
if (shiftTableLen != 0 && shiftTableLen != 128) {
- Log.e(TAG, "Error: language shift tables index " + i + " length " + shiftTableLen
+ Rlog.e(TAG, "Error: language shift tables index " + i + " length " + shiftTableLen
+ " (expected 128 or 0)");
}
@@ -638,7 +633,6 @@
* @param lengthSeptets string length in septets, not bytes
* @return String representation or null on decoding exception
*/
- @UnsupportedAppUsage
public static String gsm7BitPackedToString(byte[] pdu, int offset,
int lengthSeptets) {
return gsm7BitPackedToString(pdu, offset, lengthSeptets, 0, 0, 0);
@@ -660,17 +654,16 @@
* GSM extension table
* @return String representation or null on decoding exception
*/
- @UnsupportedAppUsage
public static String gsm7BitPackedToString(byte[] pdu, int offset,
int lengthSeptets, int numPaddingBits, int languageTable, int shiftTable) {
StringBuilder ret = new StringBuilder(lengthSeptets);
if (languageTable < 0 || languageTable > sLanguageTables.length) {
- Log.w(TAG, "unknown language table " + languageTable + ", using default");
+ Rlog.w(TAG, "unknown language table " + languageTable + ", using default");
languageTable = 0;
}
if (shiftTable < 0 || shiftTable > sLanguageShiftTables.length) {
- Log.w(TAG, "unknown single shift table " + shiftTable + ", using default");
+ Rlog.w(TAG, "unknown single shift table " + shiftTable + ", using default");
shiftTable = 0;
}
@@ -680,11 +673,11 @@
String shiftTableToChar = sLanguageShiftTables[shiftTable];
if (languageTableToChar.isEmpty()) {
- Log.w(TAG, "no language table for code " + languageTable + ", using default");
+ Rlog.w(TAG, "no language table for code " + languageTable + ", using default");
languageTableToChar = sLanguageTables[0];
}
if (shiftTableToChar.isEmpty()) {
- Log.w(TAG, "no single shift table for code " + shiftTable + ", using default");
+ Rlog.w(TAG, "no single shift table for code " + shiftTable + ", using default");
shiftTableToChar = sLanguageShiftTables[0];
}
@@ -724,7 +717,7 @@
}
}
} catch (RuntimeException ex) {
- Log.e(TAG, "Error GSM 7 bit packed: ", ex);
+ Rlog.e(TAG, "Error GSM 7 bit packed: ", ex);
return null;
}
diff --git a/src/com/android/cellbroadcastservice/GsmCellBroadcastHandler.java b/src/com/android/cellbroadcastservice/GsmCellBroadcastHandler.java
index f2fbec5..fb04fa0 100644
--- a/src/com/android/cellbroadcastservice/GsmCellBroadcastHandler.java
+++ b/src/com/android/cellbroadcastservice/GsmCellBroadcastHandler.java
@@ -282,7 +282,7 @@
if (VDBG) log("header=" + header);
TelephonyManager tm =
(TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
- tm.createForSubscriptionId(getSubIdForPhone(slotIndex));
+ tm.createForSubscriptionId(getSubIdForPhone(mContext, slotIndex));
// TODO make a systemAPI for getNetworkOperatorForSlotIndex
String plmn = tm.getSimOperator();
int lac = -1;
@@ -309,7 +309,7 @@
case SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE:
default:
- location = new SmsCbLocation(plmn);
+ location = new SmsCbLocation(plmn, -1, -1);
break;
}
diff --git a/src/com/android/cellbroadcastservice/GsmSmsCbMessage.java b/src/com/android/cellbroadcastservice/GsmSmsCbMessage.java
index 152f4e8..b91dd19 100644
--- a/src/com/android/cellbroadcastservice/GsmSmsCbMessage.java
+++ b/src/com/android/cellbroadcastservice/GsmSmsCbMessage.java
@@ -27,12 +27,12 @@
import android.content.res.Resources;
import android.telephony.CbGeoUtils.Geometry;
import android.telephony.CbGeoUtils.LatLng;
+import android.telephony.Rlog;
import android.telephony.SmsCbLocation;
import android.telephony.SmsCbMessage;
import android.telephony.SmsMessage;
import android.telephony.SubscriptionManager;
import android.util.Pair;
-import android.util.Slog;
import com.android.cellbroadcastservice.CbGeoUtils.Circle;
import com.android.cellbroadcastservice.CbGeoUtils.Polygon;
@@ -112,7 +112,7 @@
header.getSerialNumber(), location, header.getServiceCategory(), null,
getEtwsPrimaryMessage(context, header.getEtwsInfo().getWarningType()),
SmsCbMessage.MESSAGE_PRIORITY_EMERGENCY, header.getEtwsInfo(),
- header.getCmasInfo(), slotIndex, subId);
+ header.getCmasInfo(), 0, null, receivedTimeMillis, slotIndex, subId);
} else if (header.isUmtsFormat()) {
// UMTS format has only 1 PDU
byte[] pdu = pdus[0];
@@ -138,7 +138,7 @@
} catch (Exception ex) {
// Catch the exception here, the message will be considered as having no WAC
// information which means the message will be broadcasted directly.
- Slog.e(TAG, "Can't parse warning area coordinates, ex = " + ex.toString());
+ Rlog.e(TAG, "Can't parse warning area coordinates, ex = " + ex.toString());
}
}
@@ -161,7 +161,8 @@
return new SmsCbMessage(SmsCbMessage.MESSAGE_FORMAT_3GPP,
header.getGeographicalScope(), header.getSerialNumber(), location,
header.getServiceCategory(), language, sb.toString(), priority,
- header.getEtwsInfo(), header.getCmasInfo(), slotIndex, subId);
+ header.getEtwsInfo(), header.getCmasInfo(), 0, null, receivedTimeMillis,
+ slotIndex, subId);
}
}
@@ -204,7 +205,7 @@
}
return new GeoFencingTriggerMessage(type, cbIdentifiers);
} catch (Exception ex) {
- Slog.e(TAG, "create geo-fencing trigger failed, ex = " + ex.toString());
+ Rlog.e(TAG, "create geo-fencing trigger failed, ex = " + ex.toString());
return null;
}
}
diff --git a/src/com/android/cellbroadcastservice/IState.java b/src/com/android/cellbroadcastservice/IState.java
deleted file mode 100644
index a29c040..0000000
--- a/src/com/android/cellbroadcastservice/IState.java
+++ /dev/null
@@ -1,73 +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 com.android.cellbroadcastservice;
-
-import android.annotation.UnsupportedAppUsage;
-import android.os.Message;
-
-/**
- * {@hide}
- *
- * The interface for implementing states in a {@link StateMachine}
- */
-public interface IState {
-
- /**
- * Returned by processMessage to indicate the message was processed.
- */
- boolean HANDLED = true;
-
- /**
- * Returned by processMessage to indicate the message was NOT processed.
- */
- boolean NOT_HANDLED = false;
-
- /**
- * Called when a state is entered.
- */
- void enter();
-
- /**
- * Called when a state is exited.
- */
- void exit();
-
- /**
- * Called when a message is to be processed by the
- * state machine.
- *
- * This routine is never reentered thus no synchronization
- * is needed as only one processMessage method will ever be
- * executing within a state machine at any given time. This
- * does mean that processing by this routine must be completed
- * as expeditiously as possible as no subsequent messages will
- * be processed until this routine returns.
- *
- * @param msg to process
- * @return HANDLED if processing has completed and NOT_HANDLED
- * if the message wasn't processed.
- */
- boolean processMessage(Message msg);
-
- /**
- * Name of State for debugging purposes.
- *
- * @return name of state.
- */
- @UnsupportedAppUsage
- String getName();
-}
diff --git a/src/com/android/cellbroadcastservice/SmsCbHeader.java b/src/com/android/cellbroadcastservice/SmsCbHeader.java
index 8dd8807..a7efe89 100644
--- a/src/com/android/cellbroadcastservice/SmsCbHeader.java
+++ b/src/com/android/cellbroadcastservice/SmsCbHeader.java
@@ -20,8 +20,6 @@
import android.telephony.SmsCbEtwsInfo;
import android.telephony.SmsMessage;
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
import java.util.Arrays;
import java.util.Locale;
@@ -111,7 +109,6 @@
private final int mSerialNumber;
/** The Message Identifier in 3GPP is the same as the Service Category in CDMA. */
- @UnsupportedAppUsage
private final int mMessageIdentifier;
private final int mDataCodingScheme;
@@ -130,7 +127,6 @@
/** CMAS warning notification info. */
private final SmsCbCmasInfo mCmasInfo;
- @UnsupportedAppUsage
public SmsCbHeader(byte[] pdu) throws IllegalArgumentException {
if (pdu == null || pdu.length < PDU_HEADER_LENGTH) {
throw new IllegalArgumentException("Illegal PDU");
@@ -228,17 +224,14 @@
}
}
- @UnsupportedAppUsage
int getGeographicalScope() {
return mGeographicalScope;
}
- @UnsupportedAppUsage
int getSerialNumber() {
return mSerialNumber;
}
- @UnsupportedAppUsage
int getServiceCategory() {
return mMessageIdentifier;
}
@@ -251,12 +244,10 @@
return mDataCodingSchemeStructedData;
}
- @UnsupportedAppUsage
int getPageIndex() {
return mPageIndex;
}
- @UnsupportedAppUsage
int getNumberOfPages() {
return mNrOfPages;
}
diff --git a/src/com/android/cellbroadcastservice/State.java b/src/com/android/cellbroadcastservice/State.java
deleted file mode 100644
index 8d7cbc5..0000000
--- a/src/com/android/cellbroadcastservice/State.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Copyright (C) 2009 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.cellbroadcastservice;
-
-import android.annotation.UnsupportedAppUsage;
-import android.os.Message;
-
-/**
- * {@hide}
- *
- * The class for implementing states in a StateMachine
- */
-public class State implements IState {
-
- /**
- * Constructor
- */
- @UnsupportedAppUsage
- protected State() {
- }
-
- /* (non-Javadoc)
- * @see com.android.internal.util.IState#enter()
- */
- @UnsupportedAppUsage
- @Override
- public void enter() {
- }
-
- /* (non-Javadoc)
- * @see com.android.internal.util.IState#exit()
- */
- @UnsupportedAppUsage
- @Override
- public void exit() {
- }
-
- /* (non-Javadoc)
- * @see com.android.internal.util.IState#processMessage(android.os.Message)
- */
- @UnsupportedAppUsage
- @Override
- public boolean processMessage(Message msg) {
- return false;
- }
-
- /**
- * Name of State for debugging purposes.
- *
- * This default implementation returns the class name, returning
- * the instance name would better in cases where a State class
- * is used for multiple states. But normally there is one class per
- * state and the class name is sufficient and easy to get. You may
- * want to provide a setName or some other mechanism for setting
- * another name if the class name is not appropriate.
- *
- * @see com.android.internal.util.IState#processMessage(android.os.Message)
- */
- @UnsupportedAppUsage
- @Override
- public String getName() {
- String name = getClass().getName();
- int lastDollar = name.lastIndexOf('$');
- return name.substring(lastDollar + 1);
- }
-}
diff --git a/src/com/android/cellbroadcastservice/StateMachine.java b/src/com/android/cellbroadcastservice/StateMachine.java
deleted file mode 100644
index 1301ea8..0000000
--- a/src/com/android/cellbroadcastservice/StateMachine.java
+++ /dev/null
@@ -1,2183 +0,0 @@
-/**
- * Copyright (C) 2009 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.cellbroadcastservice;
-
-import android.annotation.UnsupportedAppUsage;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
-import android.os.Message;
-import android.text.TextUtils;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Vector;
-
-/**
- * {@hide}
- *
- * <p>The state machine defined here is a hierarchical state machine which processes messages
- * and can have states arranged hierarchically.</p>
- *
- * <p>A state is a <code>State</code> object and must implement
- * <code>processMessage</code> and optionally <code>enter/exit/getName</code>.
- * The enter/exit methods are equivalent to the construction and destruction
- * in Object Oriented programming and are used to perform initialization and
- * cleanup of the state respectively. The <code>getName</code> method returns the
- * name of the state; the default implementation returns the class name. It may be
- * desirable to have <code>getName</code> return the state instance name instead,
- * in particular if a particular state class has multiple instances.</p>
- *
- * <p>When a state machine is created, <code>addState</code> is used to build the
- * hierarchy and <code>setInitialState</code> is used to identify which of these
- * is the initial state. After construction the programmer calls <code>start</code>
- * which initializes and starts the state machine. The first action the StateMachine
- * is to the invoke <code>enter</code> for all of the initial state's hierarchy,
- * starting at its eldest parent. The calls to enter will be done in the context
- * of the StateMachine's Handler, not in the context of the call to start, and they
- * will be invoked before any messages are processed. For example, given the simple
- * state machine below, mP1.enter will be invoked and then mS1.enter. Finally,
- * messages sent to the state machine will be processed by the current state;
- * in our simple state machine below that would initially be mS1.processMessage.</p>
-<pre>
- mP1
- / \
- mS2 mS1 ----> initial state
-</pre>
- * <p>After the state machine is created and started, messages are sent to a state
- * machine using <code>sendMessage</code> and the messages are created using
- * <code>obtainMessage</code>. When the state machine receives a message the
- * current state's <code>processMessage</code> is invoked. In the above example
- * mS1.processMessage will be invoked first. The state may use <code>transitionTo</code>
- * to change the current state to a new state.</p>
- *
- * <p>Each state in the state machine may have a zero or one parent states. If
- * a child state is unable to handle a message it may have the message processed
- * by its parent by returning false or NOT_HANDLED. If a message is not handled by
- * a child state or any of its ancestors, <code>unhandledMessage</code> will be invoked
- * to give one last chance for the state machine to process the message.</p>
- *
- * <p>When all processing is completed a state machine may choose to call
- * <code>transitionToHaltingState</code>. When the current <code>processingMessage</code>
- * returns the state machine will transfer to an internal <code>HaltingState</code>
- * and invoke <code>halting</code>. Any message subsequently received by the state
- * machine will cause <code>haltedProcessMessage</code> to be invoked.</p>
- *
- * <p>If it is desirable to completely stop the state machine call <code>quit</code> or
- * <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents,
- * call <code>onQuitting</code> and then exit Thread/Loopers.</p>
- *
- * <p>In addition to <code>processMessage</code> each <code>State</code> has
- * an <code>enter</code> method and <code>exit</code> method which may be overridden.</p>
- *
- * <p>Since the states are arranged in a hierarchy transitioning to a new state
- * causes current states to be exited and new states to be entered. To determine
- * the list of states to be entered/exited the common parent closest to
- * the current state is found. We then exit from the current state and its
- * parent's up to but not including the common parent state and then enter all
- * of the new states below the common parent down to the destination state.
- * If there is no common parent all states are exited and then the new states
- * are entered.</p>
- *
- * <p>Two other methods that states can use are <code>deferMessage</code> and
- * <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends
- * a message but places it on the front of the queue rather than the back. The
- * <code>deferMessage</code> causes the message to be saved on a list until a
- * transition is made to a new state. At which time all of the deferred messages
- * will be put on the front of the state machine queue with the oldest message
- * at the front. These will then be processed by the new current state before
- * any other messages that are on the queue or might be added later. Both of
- * these are protected and may only be invoked from within a state machine.</p>
- *
- * <p>To illustrate some of these properties we'll use state machine with an 8
- * state hierarchy:</p>
-<pre>
- mP0
- / \
- mP1 mS0
- / \
- mS2 mS1
- / \ \
- mS3 mS4 mS5 ---> initial state
-</pre>
- * <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5.
- * So the order of calling processMessage when a message is received is mS5,
- * mS1, mP1, mP0 assuming each processMessage indicates it can't handle this
- * message by returning false or NOT_HANDLED.</p>
- *
- * <p>Now assume mS5.processMessage receives a message it can handle, and during
- * the handling determines the machine should change states. It could call
- * transitionTo(mS4) and return true or HANDLED. Immediately after returning from
- * processMessage the state machine runtime will find the common parent,
- * which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then
- * mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So
- * when the next message is received mS4.processMessage will be invoked.</p>
- *
- * <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine.
- * It responds with "Hello World" being printed to the log for every message.</p>
-<pre>
-class HelloWorld extends StateMachine {
- HelloWorld(String name) {
- super(name);
- addState(mState1);
- setInitialState(mState1);
- }
-
- public static HelloWorld makeHelloWorld() {
- HelloWorld hw = new HelloWorld("hw");
- hw.start();
- return hw;
- }
-
- class State1 extends State {
- @Override public boolean processMessage(Message message) {
- log("Hello World");
- return HANDLED;
- }
- }
- State1 mState1 = new State1();
-}
-
-void testHelloWorld() {
- HelloWorld hw = makeHelloWorld();
- hw.sendMessage(hw.obtainMessage());
-}
-</pre>
- * <p>A more interesting state machine is one with four states
- * with two independent parent states.</p>
-<pre>
- mP1 mP2
- / \
- mS2 mS1
-</pre>
- * <p>Here is a description of this state machine using pseudo code.</p>
- <pre>
-state mP1 {
- enter { log("mP1.enter"); }
- exit { log("mP1.exit"); }
- on msg {
- CMD_2 {
- send(CMD_3);
- defer(msg);
- transitionTo(mS2);
- return HANDLED;
- }
- return NOT_HANDLED;
- }
-}
-
-INITIAL
-state mS1 parent mP1 {
- enter { log("mS1.enter"); }
- exit { log("mS1.exit"); }
- on msg {
- CMD_1 {
- transitionTo(mS1);
- return HANDLED;
- }
- return NOT_HANDLED;
- }
-}
-
-state mS2 parent mP1 {
- enter { log("mS2.enter"); }
- exit { log("mS2.exit"); }
- on msg {
- CMD_2 {
- send(CMD_4);
- return HANDLED;
- }
- CMD_3 {
- defer(msg);
- transitionTo(mP2);
- return HANDLED;
- }
- return NOT_HANDLED;
- }
-}
-
-state mP2 {
- enter {
- log("mP2.enter");
- send(CMD_5);
- }
- exit { log("mP2.exit"); }
- on msg {
- CMD_3, CMD_4 { return HANDLED; }
- CMD_5 {
- transitionTo(HaltingState);
- return HANDLED;
- }
- return NOT_HANDLED;
- }
-}
-</pre>
- * <p>The implementation is below and also in StateMachineTest:</p>
-<pre>
-class Hsm1 extends StateMachine {
- public static final int CMD_1 = 1;
- public static final int CMD_2 = 2;
- public static final int CMD_3 = 3;
- public static final int CMD_4 = 4;
- public static final int CMD_5 = 5;
-
- public static Hsm1 makeHsm1() {
- log("makeHsm1 E");
- Hsm1 sm = new Hsm1("hsm1");
- sm.start();
- log("makeHsm1 X");
- return sm;
- }
-
- Hsm1(String name) {
- super(name);
- log("ctor E");
-
- // Add states, use indentation to show hierarchy
- addState(mP1);
- addState(mS1, mP1);
- addState(mS2, mP1);
- addState(mP2);
-
- // Set the initial state
- setInitialState(mS1);
- log("ctor X");
- }
-
- class P1 extends State {
- @Override public void enter() {
- log("mP1.enter");
- }
- @Override public boolean processMessage(Message message) {
- boolean retVal;
- log("mP1.processMessage what=" + message.what);
- switch(message.what) {
- case CMD_2:
- // CMD_2 will arrive in mS2 before CMD_3
- sendMessage(obtainMessage(CMD_3));
- deferMessage(message);
- transitionTo(mS2);
- retVal = HANDLED;
- break;
- default:
- // Any message we don't understand in this state invokes unhandledMessage
- retVal = NOT_HANDLED;
- break;
- }
- return retVal;
- }
- @Override public void exit() {
- log("mP1.exit");
- }
- }
-
- class S1 extends State {
- @Override public void enter() {
- log("mS1.enter");
- }
- @Override public boolean processMessage(Message message) {
- log("S1.processMessage what=" + message.what);
- if (message.what == CMD_1) {
- // Transition to ourself to show that enter/exit is called
- transitionTo(mS1);
- return HANDLED;
- } else {
- // Let parent process all other messages
- return NOT_HANDLED;
- }
- }
- @Override public void exit() {
- log("mS1.exit");
- }
- }
-
- class S2 extends State {
- @Override public void enter() {
- log("mS2.enter");
- }
- @Override public boolean processMessage(Message message) {
- boolean retVal;
- log("mS2.processMessage what=" + message.what);
- switch(message.what) {
- case(CMD_2):
- sendMessage(obtainMessage(CMD_4));
- retVal = HANDLED;
- break;
- case(CMD_3):
- deferMessage(message);
- transitionTo(mP2);
- retVal = HANDLED;
- break;
- default:
- retVal = NOT_HANDLED;
- break;
- }
- return retVal;
- }
- @Override public void exit() {
- log("mS2.exit");
- }
- }
-
- class P2 extends State {
- @Override public void enter() {
- log("mP2.enter");
- sendMessage(obtainMessage(CMD_5));
- }
- @Override public boolean processMessage(Message message) {
- log("P2.processMessage what=" + message.what);
- switch(message.what) {
- case(CMD_3):
- break;
- case(CMD_4):
- break;
- case(CMD_5):
- transitionToHaltingState();
- break;
- }
- return HANDLED;
- }
- @Override public void exit() {
- log("mP2.exit");
- }
- }
-
- @Override
- void onHalting() {
- log("halting");
- synchronized (this) {
- this.notifyAll();
- }
- }
-
- P1 mP1 = new P1();
- S1 mS1 = new S1();
- S2 mS2 = new S2();
- P2 mP2 = new P2();
-}
-</pre>
- * <p>If this is executed by sending two messages CMD_1 and CMD_2
- * (Note the synchronize is only needed because we use hsm.wait())</p>
-<pre>
-Hsm1 hsm = makeHsm1();
-synchronize(hsm) {
- hsm.sendMessage(obtainMessage(hsm.CMD_1));
- hsm.sendMessage(obtainMessage(hsm.CMD_2));
- try {
- // wait for the messages to be handled
- hsm.wait();
- } catch (InterruptedException e) {
- loge("exception while waiting " + e.getMessage());
- }
-}
-</pre>
- * <p>The output is:</p>
-<pre>
-D/hsm1 ( 1999): makeHsm1 E
-D/hsm1 ( 1999): ctor E
-D/hsm1 ( 1999): ctor X
-D/hsm1 ( 1999): mP1.enter
-D/hsm1 ( 1999): mS1.enter
-D/hsm1 ( 1999): makeHsm1 X
-D/hsm1 ( 1999): mS1.processMessage what=1
-D/hsm1 ( 1999): mS1.exit
-D/hsm1 ( 1999): mS1.enter
-D/hsm1 ( 1999): mS1.processMessage what=2
-D/hsm1 ( 1999): mP1.processMessage what=2
-D/hsm1 ( 1999): mS1.exit
-D/hsm1 ( 1999): mS2.enter
-D/hsm1 ( 1999): mS2.processMessage what=2
-D/hsm1 ( 1999): mS2.processMessage what=3
-D/hsm1 ( 1999): mS2.exit
-D/hsm1 ( 1999): mP1.exit
-D/hsm1 ( 1999): mP2.enter
-D/hsm1 ( 1999): mP2.processMessage what=3
-D/hsm1 ( 1999): mP2.processMessage what=4
-D/hsm1 ( 1999): mP2.processMessage what=5
-D/hsm1 ( 1999): mP2.exit
-D/hsm1 ( 1999): halting
-</pre>
- */
-public class StateMachine {
- // Name of the state machine and used as logging tag
- private String mName;
-
- /** Message.what value when quitting */
- private static final int SM_QUIT_CMD = -1;
-
- /** Message.what value when initializing */
- private static final int SM_INIT_CMD = -2;
-
- /**
- * Convenience constant that maybe returned by processMessage
- * to indicate the message was processed and is not to be
- * processed by parent states
- */
- public static final boolean HANDLED = true;
-
- /**
- * Convenience constant that maybe returned by processMessage
- * to indicate the message was NOT processed and is to be
- * processed by parent states
- */
- public static final boolean NOT_HANDLED = false;
-
- /**
- * StateMachine logging record.
- * {@hide}
- */
- public static class LogRec {
- private StateMachine mSm;
- private long mTime;
- private int mWhat;
- private String mInfo;
- private IState mState;
- private IState mOrgState;
- private IState mDstState;
-
- /**
- * Constructor
- *
- * @param msg
- * @param state the state which handled the message
- * @param orgState is the first state the received the message but
- * did not processes the message.
- * @param transToState is the state that was transitioned to after the message was
- * processed.
- */
- LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState,
- IState transToState) {
- update(sm, msg, info, state, orgState, transToState);
- }
-
- /**
- * Update the information in the record.
- * @param state that handled the message
- * @param orgState is the first state the received the message
- * @param dstState is the state that was the transition target when logging
- */
- public void update(StateMachine sm, Message msg, String info, IState state, IState orgState,
- IState dstState) {
- mSm = sm;
- mTime = System.currentTimeMillis();
- mWhat = (msg != null) ? msg.what : 0;
- mInfo = info;
- mState = state;
- mOrgState = orgState;
- mDstState = dstState;
- }
-
- /**
- * @return time stamp
- */
- public long getTime() {
- return mTime;
- }
-
- /**
- * @return msg.what
- */
- public long getWhat() {
- return mWhat;
- }
-
- /**
- * @return the command that was executing
- */
- public String getInfo() {
- return mInfo;
- }
-
- /**
- * @return the state that handled this message
- */
- public IState getState() {
- return mState;
- }
-
- /**
- * @return the state destination state if a transition is occurring or null if none.
- */
- public IState getDestState() {
- return mDstState;
- }
-
- /**
- * @return the original state that received the message.
- */
- public IState getOriginalState() {
- return mOrgState;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("time=");
- Calendar c = Calendar.getInstance();
- c.setTimeInMillis(mTime);
- sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
- sb.append(" processed=");
- sb.append(mState == null ? "<null>" : mState.getName());
- sb.append(" org=");
- sb.append(mOrgState == null ? "<null>" : mOrgState.getName());
- sb.append(" dest=");
- sb.append(mDstState == null ? "<null>" : mDstState.getName());
- sb.append(" what=");
- String what = mSm != null ? mSm.getWhatToString(mWhat) : "";
- if (TextUtils.isEmpty(what)) {
- sb.append(mWhat);
- sb.append("(0x");
- sb.append(Integer.toHexString(mWhat));
- sb.append(")");
- } else {
- sb.append(what);
- }
- if (!TextUtils.isEmpty(mInfo)) {
- sb.append(" ");
- sb.append(mInfo);
- }
- return sb.toString();
- }
- }
-
- /**
- * A list of log records including messages recently processed by the state machine.
- *
- * The class maintains a list of log records including messages
- * recently processed. The list is finite and may be set in the
- * constructor or by calling setSize. The public interface also
- * includes size which returns the number of recent records,
- * count which is the number of records processed since the
- * the last setSize, get which returns a record and
- * add which adds a record.
- */
- private static class LogRecords {
-
- private static final int DEFAULT_SIZE = 20;
-
- private Vector<LogRec> mLogRecVector = new Vector<LogRec>();
- private int mMaxSize = DEFAULT_SIZE;
- private int mOldestIndex = 0;
- private int mCount = 0;
- private boolean mLogOnlyTransitions = false;
-
- /**
- * private constructor use add
- */
- private LogRecords() {
- }
-
- /**
- * Set size of messages to maintain and clears all current records.
- *
- * @param maxSize number of records to maintain at anyone time.
- */
- synchronized void setSize(int maxSize) {
- // TODO: once b/28217358 is fixed, add unit tests to verify that these variables are
- // cleared after calling this method, and that subsequent calls to get() function as
- // expected.
- mMaxSize = maxSize;
- mOldestIndex = 0;
- mCount = 0;
- mLogRecVector.clear();
- }
-
- synchronized void setLogOnlyTransitions(boolean enable) {
- mLogOnlyTransitions = enable;
- }
-
- synchronized boolean logOnlyTransitions() {
- return mLogOnlyTransitions;
- }
-
- /**
- * @return the number of recent records.
- */
- synchronized int size() {
- return mLogRecVector.size();
- }
-
- /**
- * @return the total number of records processed since size was set.
- */
- synchronized int count() {
- return mCount;
- }
-
- /**
- * Clear the list of records.
- */
- synchronized void cleanup() {
- mLogRecVector.clear();
- }
-
- /**
- * @return the information on a particular record. 0 is the oldest
- * record and size()-1 is the newest record. If the index is to
- * large null is returned.
- */
- synchronized LogRec get(int index) {
- int nextIndex = mOldestIndex + index;
- if (nextIndex >= mMaxSize) {
- nextIndex -= mMaxSize;
- }
- if (nextIndex >= size()) {
- return null;
- } else {
- return mLogRecVector.get(nextIndex);
- }
- }
-
- /**
- * Add a processed message.
- *
- * @param msg
- * @param messageInfo to be stored
- * @param state that handled the message
- * @param orgState is the first state the received the message but
- * did not processes the message.
- * @param transToState is the state that was transitioned to after the message was
- * processed.
- *
- */
- synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state,
- IState orgState, IState transToState) {
- mCount += 1;
- if (mLogRecVector.size() < mMaxSize) {
- mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState));
- } else {
- LogRec pmi = mLogRecVector.get(mOldestIndex);
- mOldestIndex += 1;
- if (mOldestIndex >= mMaxSize) {
- mOldestIndex = 0;
- }
- pmi.update(sm, msg, messageInfo, state, orgState, transToState);
- }
- }
- }
-
- private static class SmHandler extends Handler {
-
- /** true if StateMachine has quit */
- private boolean mHasQuit = false;
-
- /** The debug flag */
- private boolean mDbg = false;
-
- /** The SmHandler object, identifies that message is internal */
- private static final Object sSmHandlerObj = new Object();
-
- /** The current message */
- private Message mMsg;
-
- /** A list of log records including messages this state machine has processed */
- private LogRecords mLogRecords = new LogRecords();
-
- /** true if construction of the state machine has not been completed */
- private boolean mIsConstructionCompleted;
-
- /** Stack used to manage the current hierarchy of states */
- private StateInfo[] mStateStack;
-
- /** Top of mStateStack */
- private int mStateStackTopIndex = -1;
-
- /** A temporary stack used to manage the state stack */
- private StateInfo[] mTempStateStack;
-
- /** The top of the mTempStateStack */
- private int mTempStateStackCount;
-
- /** State used when state machine is halted */
- private HaltingState mHaltingState = new HaltingState();
-
- /** State used when state machine is quitting */
- private QuittingState mQuittingState = new QuittingState();
-
- /** Reference to the StateMachine */
- private StateMachine mSm;
-
- /**
- * Information about a state.
- * Used to maintain the hierarchy.
- */
- private class StateInfo {
- /** The state */
- State state;
-
- /** The parent of this state, null if there is no parent */
- StateInfo parentStateInfo;
-
- /** True when the state has been entered and on the stack */
- boolean active;
-
- /**
- * Convert StateInfo to string
- */
- @Override
- public String toString() {
- return "state=" + state.getName() + ",active=" + active + ",parent="
- + ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName());
- }
- }
-
- /** The map of all of the states in the state machine */
- private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>();
-
- /** The initial state that will process the first message */
- private State mInitialState;
-
- /** The destination state when transitionTo has been invoked */
- private State mDestState;
-
- /**
- * Indicates if a transition is in progress
- *
- * This will be true for all calls of State.exit and all calls of State.enter except for the
- * last enter call for the current destination state.
- */
- private boolean mTransitionInProgress = false;
-
- /** The list of deferred messages */
- private ArrayList<Message> mDeferredMessages = new ArrayList<Message>();
-
- /**
- * State entered when transitionToHaltingState is called.
- */
- private class HaltingState extends State {
- @Override
- public boolean processMessage(Message msg) {
- mSm.haltedProcessMessage(msg);
- return true;
- }
- }
-
- /**
- * State entered when a valid quit message is handled.
- */
- private class QuittingState extends State {
- @Override
- public boolean processMessage(Message msg) {
- return NOT_HANDLED;
- }
- }
-
- /**
- * Handle messages sent to the state machine by calling
- * the current state's processMessage. It also handles
- * the enter/exit calls and placing any deferred messages
- * back onto the queue when transitioning to a new state.
- */
- @Override
- public final void handleMessage(Message msg) {
- if (!mHasQuit) {
- if (mSm != null && msg.what != SM_INIT_CMD && msg.what != SM_QUIT_CMD) {
- mSm.onPreHandleMessage(msg);
- }
-
- if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what);
-
- /** Save the current message */
- mMsg = msg;
-
- /** State that processed the message */
- State msgProcessedState = null;
- if (mIsConstructionCompleted || (mMsg.what == SM_QUIT_CMD)) {
- /** Normal path */
- msgProcessedState = processMsg(msg);
- } else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD)
- && (mMsg.obj == sSmHandlerObj)) {
- /** Initial one time path. */
- mIsConstructionCompleted = true;
- invokeEnterMethods(0);
- } else {
- throw new RuntimeException("StateMachine.handleMessage: "
- + "The start method not called, received msg: " + msg);
- }
- performTransitions(msgProcessedState, msg);
-
- // We need to check if mSm == null here as we could be quitting.
- if (mDbg && mSm != null) mSm.log("handleMessage: X");
-
- if (mSm != null && msg.what != SM_INIT_CMD && msg.what != SM_QUIT_CMD) {
- mSm.onPostHandleMessage(msg);
- }
- }
- }
-
- /**
- * Do any transitions
- * @param msgProcessedState is the state that processed the message
- */
- private void performTransitions(State msgProcessedState, Message msg) {
- /**
- * If transitionTo has been called, exit and then enter
- * the appropriate states. We loop on this to allow
- * enter and exit methods to use transitionTo.
- */
- State orgState = mStateStack[mStateStackTopIndex].state;
-
- /**
- * Record whether message needs to be logged before we transition and
- * and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which
- * always set msg.obj to the handler.
- */
- boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != sSmHandlerObj);
-
- if (mLogRecords.logOnlyTransitions()) {
- /** Record only if there is a transition */
- if (mDestState != null) {
- mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState,
- orgState, mDestState);
- }
- } else if (recordLogMsg) {
- /** Record message */
- mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState,
- mDestState);
- }
-
- State destState = mDestState;
- if (destState != null) {
- /**
- * Process the transitions including transitions in the enter/exit methods
- */
- while (true) {
- if (mDbg) mSm.log("handleMessage: new destination call exit/enter");
-
- /**
- * Determine the states to exit and enter and return the
- * common ancestor state of the enter/exit states. Then
- * invoke the exit methods then the enter methods.
- */
- StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState);
- // flag is cleared in invokeEnterMethods before entering the target state
- mTransitionInProgress = true;
- invokeExitMethods(commonStateInfo);
- int stateStackEnteringIndex = moveTempStateStackToStateStack();
- invokeEnterMethods(stateStackEnteringIndex);
-
- /**
- * Since we have transitioned to a new state we need to have
- * any deferred messages moved to the front of the message queue
- * so they will be processed before any other messages in the
- * message queue.
- */
- moveDeferredMessageAtFrontOfQueue();
-
- if (destState != mDestState) {
- // A new mDestState so continue looping
- destState = mDestState;
- } else {
- // No change in mDestState so we're done
- break;
- }
- }
- mDestState = null;
- }
-
- /**
- * After processing all transitions check and
- * see if the last transition was to quit or halt.
- */
- if (destState != null) {
- if (destState == mQuittingState) {
- /**
- * Call onQuitting to let subclasses cleanup.
- */
- mSm.onQuitting();
- cleanupAfterQuitting();
- } else if (destState == mHaltingState) {
- /**
- * Call onHalting() if we've transitioned to the halting
- * state. All subsequent messages will be processed in
- * in the halting state which invokes haltedProcessMessage(msg);
- */
- mSm.onHalting();
- }
- }
- }
-
- /**
- * Cleanup all the static variables and the looper after the SM has been quit.
- */
- private final void cleanupAfterQuitting() {
- if (mSm.mSmThread != null) {
- // If we made the thread then quit looper which stops the thread.
- getLooper().quit();
- mSm.mSmThread = null;
- }
-
- mSm.mSmHandler = null;
- mSm = null;
- mMsg = null;
- mLogRecords.cleanup();
- mStateStack = null;
- mTempStateStack = null;
- mStateInfo.clear();
- mInitialState = null;
- mDestState = null;
- mDeferredMessages.clear();
- mHasQuit = true;
- }
-
- /**
- * Complete the construction of the state machine.
- */
- private final void completeConstruction() {
- if (mDbg) mSm.log("completeConstruction: E");
-
- /**
- * Determine the maximum depth of the state hierarchy
- * so we can allocate the state stacks.
- */
- int maxDepth = 0;
- for (StateInfo si : mStateInfo.values()) {
- int depth = 0;
- for (StateInfo i = si; i != null; depth++) {
- i = i.parentStateInfo;
- }
- if (maxDepth < depth) {
- maxDepth = depth;
- }
- }
- if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth);
-
- mStateStack = new StateInfo[maxDepth];
- mTempStateStack = new StateInfo[maxDepth];
- setupInitialStateStack();
-
- /** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
- sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, sSmHandlerObj));
-
- if (mDbg) mSm.log("completeConstruction: X");
- }
-
- /**
- * Process the message. If the current state doesn't handle
- * it, call the states parent and so on. If it is never handled then
- * call the state machines unhandledMessage method.
- * @return the state that processed the message
- */
- private final State processMsg(Message msg) {
- StateInfo curStateInfo = mStateStack[mStateStackTopIndex];
- if (mDbg) {
- mSm.log("processMsg: " + curStateInfo.state.getName());
- }
-
- if (isQuit(msg)) {
- transitionTo(mQuittingState);
- } else {
- while (!curStateInfo.state.processMessage(msg)) {
- /**
- * Not processed
- */
- curStateInfo = curStateInfo.parentStateInfo;
- if (curStateInfo == null) {
- /**
- * No parents left so it's not handled
- */
- mSm.unhandledMessage(msg);
- break;
- }
- if (mDbg) {
- mSm.log("processMsg: " + curStateInfo.state.getName());
- }
- }
- }
- return (curStateInfo != null) ? curStateInfo.state : null;
- }
-
- /**
- * Call the exit method for each state from the top of stack
- * up to the common ancestor state.
- */
- private final void invokeExitMethods(StateInfo commonStateInfo) {
- while ((mStateStackTopIndex >= 0)
- && (mStateStack[mStateStackTopIndex] != commonStateInfo)) {
- State curState = mStateStack[mStateStackTopIndex].state;
- if (mDbg) mSm.log("invokeExitMethods: " + curState.getName());
- curState.exit();
- mStateStack[mStateStackTopIndex].active = false;
- mStateStackTopIndex -= 1;
- }
- }
-
- /**
- * Invoke the enter method starting at the entering index to top of state stack
- */
- private final void invokeEnterMethods(int stateStackEnteringIndex) {
- for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) {
- if (stateStackEnteringIndex == mStateStackTopIndex) {
- // Last enter state for transition
- mTransitionInProgress = false;
- }
- if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName());
- mStateStack[i].state.enter();
- mStateStack[i].active = true;
- }
- mTransitionInProgress = false; // ensure flag set to false if no methods called
- }
-
- /**
- * Move the deferred message to the front of the message queue.
- */
- private final void moveDeferredMessageAtFrontOfQueue() {
- /**
- * The oldest messages on the deferred list must be at
- * the front of the queue so start at the back, which
- * as the most resent message and end with the oldest
- * messages at the front of the queue.
- */
- for (int i = mDeferredMessages.size() - 1; i >= 0; i--) {
- Message curMsg = mDeferredMessages.get(i);
- if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what);
- sendMessageAtFrontOfQueue(curMsg);
- }
- mDeferredMessages.clear();
- }
-
- /**
- * Move the contents of the temporary stack to the state stack
- * reversing the order of the items on the temporary stack as
- * they are moved.
- *
- * @return index into mStateStack where entering needs to start
- */
- private final int moveTempStateStackToStateStack() {
- int startingIndex = mStateStackTopIndex + 1;
- int i = mTempStateStackCount - 1;
- int j = startingIndex;
- while (i >= 0) {
- if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j);
- mStateStack[j] = mTempStateStack[i];
- j += 1;
- i -= 1;
- }
-
- mStateStackTopIndex = j - 1;
- if (mDbg) {
- mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex
- + ",startingIndex=" + startingIndex + ",Top="
- + mStateStack[mStateStackTopIndex].state.getName());
- }
- return startingIndex;
- }
-
- /**
- * Setup the mTempStateStack with the states we are going to enter.
- *
- * This is found by searching up the destState's ancestors for a
- * state that is already active i.e. StateInfo.active == true.
- * The destStae and all of its inactive parents will be on the
- * TempStateStack as the list of states to enter.
- *
- * @return StateInfo of the common ancestor for the destState and
- * current state or null if there is no common parent.
- */
- private final StateInfo setupTempStateStackWithStatesToEnter(State destState) {
- /**
- * Search up the parent list of the destination state for an active
- * state. Use a do while() loop as the destState must always be entered
- * even if it is active. This can happen if we are exiting/entering
- * the current state.
- */
- mTempStateStackCount = 0;
- StateInfo curStateInfo = mStateInfo.get(destState);
- do {
- mTempStateStack[mTempStateStackCount++] = curStateInfo;
- curStateInfo = curStateInfo.parentStateInfo;
- } while ((curStateInfo != null) && !curStateInfo.active);
-
- if (mDbg) {
- mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount="
- + mTempStateStackCount + ",curStateInfo: " + curStateInfo);
- }
- return curStateInfo;
- }
-
- /**
- * Initialize StateStack to mInitialState.
- */
- private final void setupInitialStateStack() {
- if (mDbg) {
- mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName());
- }
-
- StateInfo curStateInfo = mStateInfo.get(mInitialState);
- for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) {
- mTempStateStack[mTempStateStackCount] = curStateInfo;
- curStateInfo = curStateInfo.parentStateInfo;
- }
-
- // Empty the StateStack
- mStateStackTopIndex = -1;
-
- moveTempStateStackToStateStack();
- }
-
- /**
- * @return current message
- */
- private final Message getCurrentMessage() {
- return mMsg;
- }
-
- /**
- * @return current state
- */
- private final IState getCurrentState() {
- return mStateStack[mStateStackTopIndex].state;
- }
-
- /**
- * Add a new state to the state machine. Bottom up addition
- * of states is allowed but the same state may only exist
- * in one hierarchy.
- *
- * @param state the state to add
- * @param parent the parent of state
- * @return stateInfo for this state
- */
- private final StateInfo addState(State state, State parent) {
- if (mDbg) {
- mSm.log("addStateInternal: E state=" + state.getName() + ",parent="
- + ((parent == null) ? "" : parent.getName()));
- }
- StateInfo parentStateInfo = null;
- if (parent != null) {
- parentStateInfo = mStateInfo.get(parent);
- if (parentStateInfo == null) {
- // Recursively add our parent as it's not been added yet.
- parentStateInfo = addState(parent, null);
- }
- }
- StateInfo stateInfo = mStateInfo.get(state);
- if (stateInfo == null) {
- stateInfo = new StateInfo();
- mStateInfo.put(state, stateInfo);
- }
-
- // Validate that we aren't adding the same state in two different hierarchies.
- if ((stateInfo.parentStateInfo != null)
- && (stateInfo.parentStateInfo != parentStateInfo)) {
- throw new RuntimeException("state already added");
- }
- stateInfo.state = state;
- stateInfo.parentStateInfo = parentStateInfo;
- stateInfo.active = false;
- if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo);
- return stateInfo;
- }
-
- /**
- * Remove a state from the state machine. Will not remove the state if it is currently
- * active or if it has any children in the hierarchy.
- * @param state the state to remove
- */
- private void removeState(State state) {
- StateInfo stateInfo = mStateInfo.get(state);
- if (stateInfo == null || stateInfo.active) {
- return;
- }
- boolean isParent = mStateInfo.values().stream()
- .filter(si -> si.parentStateInfo == stateInfo)
- .findAny()
- .isPresent();
- if (isParent) {
- return;
- }
- mStateInfo.remove(state);
- }
-
- /**
- * Constructor
- *
- * @param looper for dispatching messages
- * @param sm the hierarchical state machine
- */
- private SmHandler(Looper looper, StateMachine sm) {
- super(looper);
- mSm = sm;
-
- addState(mHaltingState, null);
- addState(mQuittingState, null);
- }
-
- /** @see StateMachine#setInitialState(State) */
- private final void setInitialState(State initialState) {
- if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName());
- mInitialState = initialState;
- }
-
- /** @see StateMachine#transitionTo(IState) */
- private final void transitionTo(IState destState) {
- if (mTransitionInProgress) {
- Log.wtf(mSm.mName, "transitionTo called while transition already in progress to " +
- mDestState + ", new target state=" + destState);
- }
- mDestState = (State) destState;
- if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName());
- }
-
- /** @see StateMachine#deferMessage(Message) */
- private final void deferMessage(Message msg) {
- if (mDbg) mSm.log("deferMessage: msg=" + msg.what);
-
- /* Copy the "msg" to "newMsg" as "msg" will be recycled */
- Message newMsg = obtainMessage();
- newMsg.copyFrom(msg);
-
- mDeferredMessages.add(newMsg);
- }
-
- /** @see StateMachine#quit() */
- private final void quit() {
- if (mDbg) mSm.log("quit:");
- sendMessage(obtainMessage(SM_QUIT_CMD, sSmHandlerObj));
- }
-
- /** @see StateMachine#quitNow() */
- private final void quitNow() {
- if (mDbg) mSm.log("quitNow:");
- sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, sSmHandlerObj));
- }
-
- /** Validate that the message was sent by quit or quitNow. */
- private final boolean isQuit(Message msg) {
- return (msg.what == SM_QUIT_CMD) && (msg.obj == sSmHandlerObj);
- }
-
- /** @see StateMachine#isDbg() */
- private final boolean isDbg() {
- return mDbg;
- }
-
- /** @see StateMachine#setDbg(boolean) */
- private final void setDbg(boolean dbg) {
- mDbg = dbg;
- }
-
- }
-
- private SmHandler mSmHandler;
- private HandlerThread mSmThread;
-
- /**
- * Initialize.
- *
- * @param looper for this state machine
- * @param name of the state machine
- */
- private void initStateMachine(String name, Looper looper) {
- mName = name;
- mSmHandler = new SmHandler(looper, this);
- }
-
- /**
- * Constructor creates a StateMachine with its own thread.
- *
- * @param name of the state machine
- */
- @UnsupportedAppUsage
- protected StateMachine(String name) {
- mSmThread = new HandlerThread(name);
- mSmThread.start();
- Looper looper = mSmThread.getLooper();
-
- initStateMachine(name, looper);
- }
-
- /**
- * Constructor creates a StateMachine using the looper.
- *
- * @param name of the state machine
- */
- @UnsupportedAppUsage
- protected StateMachine(String name, Looper looper) {
- initStateMachine(name, looper);
- }
-
- /**
- * Constructor creates a StateMachine using the handler.
- *
- * @param name of the state machine
- */
- @UnsupportedAppUsage
- protected StateMachine(String name, Handler handler) {
- initStateMachine(name, handler.getLooper());
- }
-
- /**
- * Notifies subclass that the StateMachine handler is about to process the Message msg
- * @param msg The message that is being handled
- */
- protected void onPreHandleMessage(Message msg) {
- }
-
- /**
- * Notifies subclass that the StateMachine handler has finished processing the Message msg and
- * has possibly transitioned to a new state.
- * @param msg The message that is being handled
- */
- protected void onPostHandleMessage(Message msg) {
- }
-
- /**
- * Add a new state to the state machine
- * @param state the state to add
- * @param parent the parent of state
- */
- public final void addState(State state, State parent) {
- mSmHandler.addState(state, parent);
- }
-
- /**
- * Add a new state to the state machine, parent will be null
- * @param state to add
- */
- @UnsupportedAppUsage
- public final void addState(State state) {
- mSmHandler.addState(state, null);
- }
-
- /**
- * Removes a state from the state machine, unless it is currently active or if it has children.
- * @param state state to remove
- */
- public final void removeState(State state) {
- mSmHandler.removeState(state);
- }
-
- /**
- * Set the initial state. This must be invoked before
- * and messages are sent to the state machine.
- *
- * @param initialState is the state which will receive the first message.
- */
- @UnsupportedAppUsage
- public final void setInitialState(State initialState) {
- mSmHandler.setInitialState(initialState);
- }
-
- /**
- * @return current message
- */
- public final Message getCurrentMessage() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return null;
- return smh.getCurrentMessage();
- }
-
- /**
- * @return current state
- */
- public final IState getCurrentState() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return null;
- return smh.getCurrentState();
- }
-
- /**
- * transition to destination state. Upon returning
- * from processMessage the current state's exit will
- * be executed and upon the next message arriving
- * destState.enter will be invoked.
- *
- * this function can also be called inside the enter function of the
- * previous transition target, but the behavior is undefined when it is
- * called mid-way through a previous transition (for example, calling this
- * in the enter() routine of a intermediate node when the current transition
- * target is one of the nodes descendants).
- *
- * @param destState will be the state that receives the next message.
- */
- @UnsupportedAppUsage
- public final void transitionTo(IState destState) {
- mSmHandler.transitionTo(destState);
- }
-
- /**
- * transition to halt state. Upon returning
- * from processMessage we will exit all current
- * states, execute the onHalting() method and then
- * for all subsequent messages haltedProcessMessage
- * will be called.
- */
- public final void transitionToHaltingState() {
- mSmHandler.transitionTo(mSmHandler.mHaltingState);
- }
-
- /**
- * Defer this message until next state transition.
- * Upon transitioning all deferred messages will be
- * placed on the queue and reprocessed in the original
- * order. (i.e. The next state the oldest messages will
- * be processed first)
- *
- * @param msg is deferred until the next transition.
- */
- public final void deferMessage(Message msg) {
- mSmHandler.deferMessage(msg);
- }
-
- /**
- * Called when message wasn't handled
- *
- * @param msg that couldn't be handled.
- */
- protected void unhandledMessage(Message msg) {
- if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what);
- }
-
- /**
- * Called for any message that is received after
- * transitionToHalting is called.
- */
- protected void haltedProcessMessage(Message msg) {
- }
-
- /**
- * This will be called once after handling a message that called
- * transitionToHalting. All subsequent messages will invoke
- * {@link StateMachine#haltedProcessMessage(Message)}
- */
- protected void onHalting() {
- }
-
- /**
- * This will be called once after a quit message that was NOT handled by
- * the derived StateMachine. The StateMachine will stop and any subsequent messages will be
- * ignored. In addition, if this StateMachine created the thread, the thread will
- * be stopped after this method returns.
- */
- protected void onQuitting() {
- }
-
- /**
- * @return the name
- */
- public final String getName() {
- return mName;
- }
-
- /**
- * Set number of log records to maintain and clears all current records.
- *
- * @param maxSize number of messages to maintain at anyone time.
- */
- public final void setLogRecSize(int maxSize) {
- mSmHandler.mLogRecords.setSize(maxSize);
- }
-
- /**
- * Set to log only messages that cause a state transition
- *
- * @param enable {@code true} to enable, {@code false} to disable
- */
- public final void setLogOnlyTransitions(boolean enable) {
- mSmHandler.mLogRecords.setLogOnlyTransitions(enable);
- }
-
- /**
- * @return the number of log records currently readable
- */
- public final int getLogRecSize() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return 0;
- return smh.mLogRecords.size();
- }
-
- /**
- * @return the number of log records we can store
- */
- @VisibleForTesting
- public final int getLogRecMaxSize() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return 0;
- return smh.mLogRecords.mMaxSize;
- }
-
- /**
- * @return the total number of records processed
- */
- public final int getLogRecCount() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return 0;
- return smh.mLogRecords.count();
- }
-
- /**
- * @return a log record, or null if index is out of range
- */
- public final LogRec getLogRec(int index) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return null;
- return smh.mLogRecords.get(index);
- }
-
- /**
- * @return a copy of LogRecs as a collection
- */
- public final Collection<LogRec> copyLogRecs() {
- Vector<LogRec> vlr = new Vector<LogRec>();
- SmHandler smh = mSmHandler;
- if (smh != null) {
- for (LogRec lr : smh.mLogRecords.mLogRecVector) {
- vlr.add(lr);
- }
- }
- return vlr;
- }
-
- /**
- * Add the string to LogRecords.
- *
- * @param string
- */
- public void addLogRec(String string) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
- smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(),
- smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState);
- }
-
- /**
- * @return true if msg should be saved in the log, default is true.
- */
- protected boolean recordLogRec(Message msg) {
- return true;
- }
-
- /**
- * Return a string to be logged by LogRec, default
- * is an empty string. Override if additional information is desired.
- *
- * @param msg that was processed
- * @return information to be logged as a String
- */
- protected String getLogRecString(Message msg) {
- return "";
- }
-
- /**
- * @return the string for msg.what
- */
- protected String getWhatToString(int what) {
- return null;
- }
-
- /**
- * @return Handler, maybe null if state machine has quit.
- */
- public final Handler getHandler() {
- return mSmHandler;
- }
-
- /**
- * Get a message and set Message.target state machine handler.
- *
- * Note: The handler can be null if the state machine has quit,
- * which means target will be null and may cause a AndroidRuntimeException
- * in MessageQueue#enqueMessage if sent directly or if sent using
- * StateMachine#sendMessage the message will just be ignored.
- *
- * @return A Message object from the global pool
- */
- public final Message obtainMessage() {
- return Message.obtain(mSmHandler);
- }
-
- /**
- * Get a message and set Message.target state machine handler, what.
- *
- * Note: The handler can be null if the state machine has quit,
- * which means target will be null and may cause a AndroidRuntimeException
- * in MessageQueue#enqueMessage if sent directly or if sent using
- * StateMachine#sendMessage the message will just be ignored.
- *
- * @param what is the assigned to Message.what.
- * @return A Message object from the global pool
- */
- public final Message obtainMessage(int what) {
- return Message.obtain(mSmHandler, what);
- }
-
- /**
- * Get a message and set Message.target state machine handler,
- * what and obj.
- *
- * Note: The handler can be null if the state machine has quit,
- * which means target will be null and may cause a AndroidRuntimeException
- * in MessageQueue#enqueMessage if sent directly or if sent using
- * StateMachine#sendMessage the message will just be ignored.
- *
- * @param what is the assigned to Message.what.
- * @param obj is assigned to Message.obj.
- * @return A Message object from the global pool
- */
- public final Message obtainMessage(int what, Object obj) {
- return Message.obtain(mSmHandler, what, obj);
- }
-
- /**
- * Get a message and set Message.target state machine handler,
- * what, arg1 and arg2
- *
- * Note: The handler can be null if the state machine has quit,
- * which means target will be null and may cause a AndroidRuntimeException
- * in MessageQueue#enqueMessage if sent directly or if sent using
- * StateMachine#sendMessage the message will just be ignored.
- *
- * @param what is assigned to Message.what
- * @param arg1 is assigned to Message.arg1
- * @return A Message object from the global pool
- */
- public final Message obtainMessage(int what, int arg1) {
- // use this obtain so we don't match the obtain(h, what, Object) method
- return Message.obtain(mSmHandler, what, arg1, 0);
- }
-
- /**
- * Get a message and set Message.target state machine handler,
- * what, arg1 and arg2
- *
- * Note: The handler can be null if the state machine has quit,
- * which means target will be null and may cause a AndroidRuntimeException
- * in MessageQueue#enqueMessage if sent directly or if sent using
- * StateMachine#sendMessage the message will just be ignored.
- *
- * @param what is assigned to Message.what
- * @param arg1 is assigned to Message.arg1
- * @param arg2 is assigned to Message.arg2
- * @return A Message object from the global pool
- */
- @UnsupportedAppUsage
- public final Message obtainMessage(int what, int arg1, int arg2) {
- return Message.obtain(mSmHandler, what, arg1, arg2);
- }
-
- /**
- * Get a message and set Message.target state machine handler,
- * what, arg1, arg2 and obj
- *
- * Note: The handler can be null if the state machine has quit,
- * which means target will be null and may cause a AndroidRuntimeException
- * in MessageQueue#enqueMessage if sent directly or if sent using
- * StateMachine#sendMessage the message will just be ignored.
- *
- * @param what is assigned to Message.what
- * @param arg1 is assigned to Message.arg1
- * @param arg2 is assigned to Message.arg2
- * @param obj is assigned to Message.obj
- * @return A Message object from the global pool
- */
- @UnsupportedAppUsage
- public final Message obtainMessage(int what, int arg1, int arg2, Object obj) {
- return Message.obtain(mSmHandler, what, arg1, arg2, obj);
- }
-
- /**
- * Enqueue a message to this state machine.
- *
- * Message is ignored if state machine has quit.
- */
- @UnsupportedAppUsage
- public void sendMessage(int what) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessage(obtainMessage(what));
- }
-
- /**
- * Enqueue a message to this state machine.
- *
- * Message is ignored if state machine has quit.
- */
- @UnsupportedAppUsage
- public void sendMessage(int what, Object obj) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessage(obtainMessage(what, obj));
- }
-
- /**
- * Enqueue a message to this state machine.
- *
- * Message is ignored if state machine has quit.
- */
- @UnsupportedAppUsage
- public void sendMessage(int what, int arg1) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessage(obtainMessage(what, arg1));
- }
-
- /**
- * Enqueue a message to this state machine.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessage(int what, int arg1, int arg2) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessage(obtainMessage(what, arg1, arg2));
- }
-
- /**
- * Enqueue a message to this state machine.
- *
- * Message is ignored if state machine has quit.
- */
- @UnsupportedAppUsage
- public void sendMessage(int what, int arg1, int arg2, Object obj) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessage(obtainMessage(what, arg1, arg2, obj));
- }
-
- /**
- * Enqueue a message to this state machine.
- *
- * Message is ignored if state machine has quit.
- */
- @UnsupportedAppUsage
- public void sendMessage(Message msg) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessage(msg);
- }
-
- /**
- * Enqueue a message to this state machine after a delay.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessageDelayed(int what, long delayMillis) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageDelayed(obtainMessage(what), delayMillis);
- }
-
- /**
- * Enqueue a message to this state machine after a delay.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessageDelayed(int what, Object obj, long delayMillis) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis);
- }
-
- /**
- * Enqueue a message to this state machine after a delay.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessageDelayed(int what, int arg1, long delayMillis) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageDelayed(obtainMessage(what, arg1), delayMillis);
- }
-
- /**
- * Enqueue a message to this state machine after a delay.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageDelayed(obtainMessage(what, arg1, arg2), delayMillis);
- }
-
- /**
- * Enqueue a message to this state machine after a delay.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessageDelayed(int what, int arg1, int arg2, Object obj,
- long delayMillis) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageDelayed(obtainMessage(what, arg1, arg2, obj), delayMillis);
- }
-
- /**
- * Enqueue a message to this state machine after a delay.
- *
- * Message is ignored if state machine has quit.
- */
- public void sendMessageDelayed(Message msg, long delayMillis) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageDelayed(msg, delayMillis);
- }
-
- /**
- * Enqueue a message to the front of the queue for this state machine.
- * Protected, may only be called by instances of StateMachine.
- *
- * Message is ignored if state machine has quit.
- */
- protected final void sendMessageAtFrontOfQueue(int what) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageAtFrontOfQueue(obtainMessage(what));
- }
-
- /**
- * Enqueue a message to the front of the queue for this state machine.
- * Protected, may only be called by instances of StateMachine.
- *
- * Message is ignored if state machine has quit.
- */
- protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
- }
-
- /**
- * Enqueue a message to the front of the queue for this state machine.
- * Protected, may only be called by instances of StateMachine.
- *
- * Message is ignored if state machine has quit.
- */
- protected final void sendMessageAtFrontOfQueue(int what, int arg1) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1));
- }
-
-
- /**
- * Enqueue a message to the front of the queue for this state machine.
- * Protected, may only be called by instances of StateMachine.
- *
- * Message is ignored if state machine has quit.
- */
- protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2));
- }
-
- /**
- * Enqueue a message to the front of the queue for this state machine.
- * Protected, may only be called by instances of StateMachine.
- *
- * Message is ignored if state machine has quit.
- */
- protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2, Object obj) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2, obj));
- }
-
- /**
- * Enqueue a message to the front of the queue for this state machine.
- * Protected, may only be called by instances of StateMachine.
- *
- * Message is ignored if state machine has quit.
- */
- protected final void sendMessageAtFrontOfQueue(Message msg) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.sendMessageAtFrontOfQueue(msg);
- }
-
- /**
- * Removes a message from the message queue.
- * Protected, may only be called by instances of StateMachine.
- */
- protected final void removeMessages(int what) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.removeMessages(what);
- }
-
- /**
- * Removes a message from the deferred messages queue.
- */
- protected final void removeDeferredMessages(int what) {
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- Iterator<Message> iterator = smh.mDeferredMessages.iterator();
- while (iterator.hasNext()) {
- Message msg = iterator.next();
- if (msg.what == what) iterator.remove();
- }
- }
-
- /**
- * Check if there are any pending messages with code 'what' in deferred messages queue.
- */
- protected final boolean hasDeferredMessages(int what) {
- SmHandler smh = mSmHandler;
- if (smh == null) return false;
-
- Iterator<Message> iterator = smh.mDeferredMessages.iterator();
- while (iterator.hasNext()) {
- Message msg = iterator.next();
- if (msg.what == what) return true;
- }
-
- return false;
- }
-
- /**
- * Check if there are any pending posts of messages with code 'what' in
- * the message queue. This does NOT check messages in deferred message queue.
- */
- protected final boolean hasMessages(int what) {
- SmHandler smh = mSmHandler;
- if (smh == null) return false;
-
- return smh.hasMessages(what);
- }
-
- /**
- * Validate that the message was sent by
- * {@link StateMachine#quit} or {@link StateMachine#quitNow}.
- */
- protected final boolean isQuit(Message msg) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return msg.what == SM_QUIT_CMD;
-
- return smh.isQuit(msg);
- }
-
- /**
- * Quit the state machine after all currently queued up messages are processed.
- */
- public final void quit() {
- // mSmHandler can be null if the state machine is already stopped.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.quit();
- }
-
- /**
- * Quit the state machine immediately all currently queued messages will be discarded.
- */
- public final void quitNow() {
- // mSmHandler can be null if the state machine is already stopped.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.quitNow();
- }
-
- /**
- * @return if debugging is enabled
- */
- public boolean isDbg() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return false;
-
- return smh.isDbg();
- }
-
- /**
- * Set debug enable/disabled.
- *
- * @param dbg is true to enable debugging.
- */
- public void setDbg(boolean dbg) {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- smh.setDbg(dbg);
- }
-
- /**
- * Start the state machine.
- */
- @UnsupportedAppUsage
- public void start() {
- // mSmHandler can be null if the state machine has quit.
- SmHandler smh = mSmHandler;
- if (smh == null) return;
-
- /** Send the complete construction message */
- smh.completeConstruction();
- }
-
- /**
- * Dump the current state.
- *
- * @param fd
- * @param pw
- * @param args
- */
- @UnsupportedAppUsage
- public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
- pw.println(getName() + ":");
- pw.println(" total records=" + getLogRecCount());
- for (int i = 0; i < getLogRecSize(); i++) {
- pw.println(" rec[" + i + "]: " + getLogRec(i).toString());
- pw.flush();
- }
- pw.println("curState=" + getCurrentState().getName());
- }
-
- @Override
- public String toString() {
- String name = "(null)";
- String state = "(null)";
- try {
- name = mName.toString();
- state = mSmHandler.getCurrentState().getName().toString();
- } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
- // Will use default(s) initialized above.
- }
- return "name=" + name + " state=" + state;
- }
-
- /**
- * Log with debug and add to the LogRecords.
- *
- * @param s is string log
- */
- protected void logAndAddLogRec(String s) {
- addLogRec(s);
- log(s);
- }
-
- /**
- * Log with debug
- *
- * @param s is string log
- */
- protected void log(String s) {
- Log.d(mName, s);
- }
-
- /**
- * Log with debug attribute
- *
- * @param s is string log
- */
- protected void logd(String s) {
- Log.d(mName, s);
- }
-
- /**
- * Log with verbose attribute
- *
- * @param s is string log
- */
- protected void logv(String s) {
- Log.v(mName, s);
- }
-
- /**
- * Log with info attribute
- *
- * @param s is string log
- */
- protected void logi(String s) {
- Log.i(mName, s);
- }
-
- /**
- * Log with warning attribute
- *
- * @param s is string log
- */
- protected void logw(String s) {
- Log.w(mName, s);
- }
-
- /**
- * Log with error attribute
- *
- * @param s is string log
- */
- protected void loge(String s) {
- Log.e(mName, s);
- }
-
- /**
- * Log with error attribute
- *
- * @param s is string log
- * @param e is a Throwable which logs additional information.
- */
- protected void loge(String s, Throwable e) {
- Log.e(mName, s, e);
- }
-}
diff --git a/src/com/android/cellbroadcastservice/UserData.java b/src/com/android/cellbroadcastservice/UserData.java
index 7cbf320..d9e3aaf 100644
--- a/src/com/android/cellbroadcastservice/UserData.java
+++ b/src/com/android/cellbroadcastservice/UserData.java
@@ -18,10 +18,6 @@
import android.util.SparseIntArray;
-import com.android.internal.util.HexDump;
-
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
public class UserData {
/**
@@ -79,6 +75,12 @@
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~'};
+
+ private static final char[] HEX_DIGITS =
+ {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+ private static final char[] HEX_LOWER_CASE_DIGITS =
+ {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
/**
* Character to use when forced to encode otherwise unencodable
* characters, meaning those not in the respective ASCII or GSM
@@ -93,7 +95,6 @@
public static final int PRINTABLE_ASCII_MIN_INDEX = 0x20;
public static final int ASCII_NL_INDEX = 0x0A;
public static final int ASCII_CR_INDEX = 0x0D;
- @UnsupportedAppUsage
public static final SparseIntArray charToAscii = new SparseIntArray();
static {
for (int i = 0; i < ASCII_MAP.length; i++) {
@@ -103,7 +104,6 @@
charToAscii.put('\r', ASCII_CR_INDEX);
}
- @UnsupportedAppUsage
public UserData() {
}
@@ -117,15 +117,12 @@
/**
* Contains the data header of the user data
*/
- @UnsupportedAppUsage
public SmsHeader userDataHeader;
/**
* Contains the data encoding type for the SMS message
*/
- @UnsupportedAppUsage
public int msgEncoding;
- @UnsupportedAppUsage
public boolean msgEncodingSet = false;
public int msgType;
@@ -135,16 +132,13 @@
*/
public int paddingBits;
- @UnsupportedAppUsage
public int numFields;
/**
* Contains the user data of a SMS message
* (See 3GPP2 C.S0015-B, v2, 4.5.2)
*/
- @UnsupportedAppUsage
public byte[] payload;
- @UnsupportedAppUsage
public String payloadStr;
@Override
@@ -156,10 +150,25 @@
builder.append(", paddingBits=" + paddingBits);
builder.append(", numFields=" + numFields);
builder.append(", userDataHeader=" + userDataHeader);
- builder.append(", payload='" + HexDump.toHexString(payload) + "'");
+ builder.append(", payload='" + toHexString(payload) + "'");
builder.append(", payloadStr='" + payloadStr + "'");
builder.append(" }");
return builder.toString();
}
+ private static String toHexString(byte[] array) {
+ return toHexString(array, 0, array.length, true);
+ }
+
+ private static String toHexString(byte[] array, int offset, int length, boolean upperCase) {
+ char[] digits = upperCase ? HEX_DIGITS : HEX_LOWER_CASE_DIGITS;
+ char[] buf = new char[length * 2];
+ int bufIndex = 0;
+ for (int i = offset; i < offset + length; i++) {
+ byte b = array[i];
+ buf[bufIndex++] = digits[(b >>> 4) & 0x0F];
+ buf[bufIndex++] = digits[b & 0x0F];
+ }
+ return new String(buf);
+ }
}
diff --git a/src/com/android/cellbroadcastservice/WakeLockStateMachine.java b/src/com/android/cellbroadcastservice/WakeLockStateMachine.java
index 1874cef..1d08f54 100644
--- a/src/com/android/cellbroadcastservice/WakeLockStateMachine.java
+++ b/src/com/android/cellbroadcastservice/WakeLockStateMachine.java
@@ -16,7 +16,6 @@
package com.android.cellbroadcastservice;
-import android.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -24,7 +23,7 @@
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemProperties;
-import android.util.Log;
+import android.telephony.Rlog;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
@@ -55,7 +54,6 @@
/** Broadcast not required due to geo-fencing check */
static final int EVENT_BROADCAST_NOT_REQUIRED = 4;
- @UnsupportedAppUsage
protected Context mContext;
protected AtomicInteger mReceiverCount = new AtomicInteger(0);
@@ -64,7 +62,6 @@
private static final int WAKE_LOCK_TIMEOUT = 3000;
private final DefaultState mDefaultState = new DefaultState();
- @UnsupportedAppUsage
private final IdleState mIdleState = new IdleState();
private final WaitingState mWaitingState = new WaitingState();
@@ -236,10 +233,9 @@
* Log with debug level.
* @param s the string to log
*/
- @UnsupportedAppUsage
@Override
protected void log(String s) {
- Log.d(getName(), s);
+ Rlog.d(getName(), s);
}
/**
@@ -248,7 +244,7 @@
*/
@Override
protected void loge(String s) {
- Log.e(getName(), s);
+ Rlog.e(getName(), s);
}
/**
@@ -258,6 +254,6 @@
*/
@Override
protected void loge(String s, Throwable e) {
- Log.e(getName(), s, e);
+ Rlog.e(getName(), s, e);
}
}
diff --git a/tests/Android.bp b/tests/Android.bp
index f59dde6..ef9568e 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -15,7 +15,7 @@
],
srcs: ["src/**/*.java", ":cellbroadcast-shared-srcs"],
platform_apis: true,
- test_suites: ["device-tests"],
+ test_suites: ["device-tests", "mts"],
certificate: "platform",
instrumentation_for: "CellBroadcastServiceModule",
}
diff --git a/tests/src/com/android/cellbroadcastservice/tests/CdmaSmsMessageTest.java b/tests/src/com/android/cellbroadcastservice/tests/CdmaSmsMessageTest.java
index 171d437..7e34a40 100644
--- a/tests/src/com/android/cellbroadcastservice/tests/CdmaSmsMessageTest.java
+++ b/tests/src/com/android/cellbroadcastservice/tests/CdmaSmsMessageTest.java
@@ -18,12 +18,12 @@
import android.content.Context;
import android.hardware.radio.V1_0.CdmaSmsMessage;
+import android.telephony.Rlog;
import android.telephony.SmsCbCmasInfo;
import android.telephony.SmsCbMessage;
import android.telephony.cdma.CdmaSmsCbProgramData;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import android.util.Log;
import com.android.cellbroadcastservice.BearerData;
import com.android.cellbroadcastservice.DefaultCellBroadcastService;
@@ -650,10 +650,10 @@
//SmsCbMessage cbMessage = msg.parseBroadcastSms("", 0);
// with random input, cbMessage will almost always be null (log when it isn't)
if (cbMessage != null) {
- Log.d(TAG, "success: " + cbMessage);
+ Rlog.d(TAG, "success: " + cbMessage);
}
} catch (Exception e) {
- Log.d(TAG, "exception thrown", e);
+ Rlog.d(TAG, "exception thrown", e);
fail("Exception in decoder at run " + run + " length " + len + ": " + e);
}
}
@@ -686,7 +686,7 @@
msg.getEnvelopeBearerData(), msg.getEnvelopeServiceCategory());
//SmsCbMessage cbMessage = msg.parseBroadcastSms("", 0);
} catch (Exception e) {
- Log.d(TAG, "exception thrown", e);
+ Rlog.d(TAG, "exception thrown", e);
fail("Exception in decoder at run " + run + " length " + len + ": " + e);
}
}
diff --git a/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTest.java b/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTest.java
index b5c3faf..b19d55f 100644
--- a/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTest.java
+++ b/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTest.java
@@ -27,9 +27,9 @@
import android.database.Cursor;
import android.net.Uri;
import android.provider.Telephony.CellBroadcasts;
+import android.telephony.Rlog;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
-import android.util.Log;
import com.android.cellbroadcastservice.CellBroadcastProvider;
import com.android.cellbroadcastservice.CellBroadcastProvider.PermissionChecker;
@@ -325,7 +325,7 @@
@Override
public Object getSystemService(String name) {
- Log.d(TAG, "getSystemService: returning null");
+ Rlog.d(TAG, "getSystemService: returning null");
return null;
}
diff --git a/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTestable.java b/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTestable.java
index b50ccb0..06fde6b 100644
--- a/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTestable.java
+++ b/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastProviderTestable.java
@@ -20,7 +20,7 @@
import android.content.pm.ProviderInfo;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
-import android.util.Log;
+import android.telephony.Rlog;
import androidx.test.InstrumentationRegistry;
@@ -36,7 +36,7 @@
@Override
public boolean onCreate() {
// DO NOT call super.onCreate(), otherwise the permission checker will be override.
- Log.d(TAG, "CellBroadcastProviderTestable onCreate");
+ Rlog.d(TAG, "CellBroadcastProviderTestable onCreate");
mDbHelper = new InMemoryCellBroadcastProviderDbHelper();
return true;
}
@@ -55,7 +55,7 @@
@Override
public void onCreate(SQLiteDatabase db) {
- Log.d(TAG, "IN MEMORY DB CREATED");
+ Rlog.d(TAG, "IN MEMORY DB CREATED");
db.execSQL(getStringForCellBroadcastTableCreation(CELL_BROADCASTS_TABLE_NAME));
}
diff --git a/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastServiceTestBase.java b/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastServiceTestBase.java
index 009986e..c230f2d 100644
--- a/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastServiceTestBase.java
+++ b/tests/src/com/android/cellbroadcastservice/tests/CellBroadcastServiceTestBase.java
@@ -18,6 +18,7 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
@@ -135,6 +136,7 @@
return null;
}).when(mMockedContext).registerReceiver(
any(BroadcastReceiver.class), any(IntentFilter.class));
+ doReturn(true).when(mMockedLocationManager).isProviderEnabled(anyString());
}
protected void tearDown() throws Exception {
diff --git a/tests/src/com/android/cellbroadcastservice/tests/GsmCellBroadcastHandlerTest.java b/tests/src/com/android/cellbroadcastservice/tests/GsmCellBroadcastHandlerTest.java
index 65f0c4b..1fefbbf 100644
--- a/tests/src/com/android/cellbroadcastservice/tests/GsmCellBroadcastHandlerTest.java
+++ b/tests/src/com/android/cellbroadcastservice/tests/GsmCellBroadcastHandlerTest.java
@@ -21,6 +21,7 @@
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.ContentValues;
@@ -28,6 +29,8 @@
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MatrixCursor;
+import android.location.Location;
+import android.location.LocationRequest;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
@@ -52,8 +55,10 @@
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
+import org.mockito.Mockito;
import java.util.Map;
+import java.util.function.Consumer;
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -168,6 +173,7 @@
@Test
@SmallTest
public void testTriggerMessage() throws Exception {
+ doReturn(false).when(mMockedLocationManager).isProviderEnabled(anyString());
final byte[] pdu = hexStringToBytes("0001113001010010C0111204D2");
mGsmCellBroadcastHandler.onGsmCellBroadcastSms(0, pdu);
mTestableLooper.processAllMessages();
@@ -202,4 +208,27 @@
verify(mMockedContext, never()).sendOrderedBroadcast(any(), anyString(), anyString(),
any(), any(), anyInt(), any(), any());
}
+
+ @Test
+ @SmallTest
+ public void testGeofencingAlertOutOfPolygon() {
+ final byte[] pdu = hexStringToBytes("01111D7090010254747A0E4ACF416110B538A582DE6650906AA28"
+ + "2AE6979995D9ECF41C576597E2EBBC77950905D96D3D3EE33689A9FD3CB6D1708CA2E87E76550FAE"
+ + "C7ECBCB203ABA0C6A97E7F3F0B9EC02C15CB5769A5D0652A030FB1ECECF5D5076393C2F83C8E9B9B"
+ + "C7C0ECBC9203A3A3D07B5CBF379F85C06E16030580D660BB662B51A0D57CC3500000000000000000"
+ + "0000000000000000000000000000000000000000000000000003021002078B53B6CA4B84B53988A4"
+ + "B86B53958A4C2DB53B54A4C28B53B6CA4B840100CFF");
+ mGsmCellBroadcastHandler.onGsmCellBroadcastSms(0, pdu);
+ mTestableLooper.processAllMessages();
+
+ ArgumentCaptor<Consumer<Location>> captor = ArgumentCaptor.forClass(Consumer.class);
+ verify(mMockedLocationManager, times(2)).getCurrentLocation(
+ any(LocationRequest.class), any(), any(), captor.capture());
+
+ Consumer<Location> consumer = captor.getValue();
+ consumer.accept(Mockito.mock(Location.class));
+
+ verify(mMockedContext, never()).sendOrderedBroadcast(any(), anyString(), anyString(),
+ any(), any(), anyInt(), any(), any());
+ }
}
diff --git a/tests/src/com/android/cellbroadcastservice/tests/GsmSmsCbMessageTest.java b/tests/src/com/android/cellbroadcastservice/tests/GsmSmsCbMessageTest.java
index 73820b6..1547a56 100644
--- a/tests/src/com/android/cellbroadcastservice/tests/GsmSmsCbMessageTest.java
+++ b/tests/src/com/android/cellbroadcastservice/tests/GsmSmsCbMessageTest.java
@@ -17,13 +17,13 @@
package com.android.cellbroadcastservice.tests;
import android.telephony.CbGeoUtils;
+import android.telephony.Rlog;
import android.telephony.SmsCbCmasInfo;
import android.telephony.SmsCbEtwsInfo;
import android.telephony.SmsCbLocation;
import android.telephony.SmsCbMessage;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import android.util.Log;
import androidx.test.InstrumentationRegistry;
@@ -77,27 +77,27 @@
String message = GsmSmsCbMessage.getEtwsPrimaryMessage(mMockedContext,
SmsCbEtwsInfo.ETWS_WARNING_TYPE_EARTHQUAKE);
- Log.d("GsmSmsCbMessageTest", "earthquake message=" + message);
+ Rlog.d("GsmSmsCbMessageTest", "earthquake message=" + message);
assertEquals(testMessage1, message);
message = GsmSmsCbMessage.getEtwsPrimaryMessage(mMockedContext,
SmsCbEtwsInfo.ETWS_WARNING_TYPE_TSUNAMI);
- Log.d("GsmSmsCbMessageTest", "tsunami message=" + message);
+ Rlog.d("GsmSmsCbMessageTest", "tsunami message=" + message);
assertEquals(testMessage2, message);
message = GsmSmsCbMessage.getEtwsPrimaryMessage(mMockedContext,
SmsCbEtwsInfo.ETWS_WARNING_TYPE_EARTHQUAKE_AND_TSUNAMI);
- Log.d("GsmSmsCbMessageTest", "earthquake and tsunami message=" + message);
+ Rlog.d("GsmSmsCbMessageTest", "earthquake and tsunami message=" + message);
assertEquals(testMessage3, message);
message = GsmSmsCbMessage.getEtwsPrimaryMessage(mMockedContext,
SmsCbEtwsInfo.ETWS_WARNING_TYPE_TEST_MESSAGE);
- Log.d("GsmSmsCbMessageTest", "test message=" + message);
+ Rlog.d("GsmSmsCbMessageTest", "test message=" + message);
assertEquals(testMessage4, message);
message = GsmSmsCbMessage.getEtwsPrimaryMessage(mMockedContext,
SmsCbEtwsInfo.ETWS_WARNING_TYPE_OTHER_EMERGENCY);
- Log.d("GsmSmsCbMessageTest", "others message=" + message);
+ Rlog.d("GsmSmsCbMessageTest", "others message=" + message);
assertEquals(testMessage5, message);
}
@@ -126,7 +126,7 @@
SmsCbMessage msg = GsmSmsCbMessage.createSmsCbMessage(mMockedContext, header, null, pdus,
0);
- Log.d(TAG, "msg=" + msg);
+ Rlog.d(TAG, "msg=" + msg);
assertEquals(SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE,
msg.getGeographicalScope());
@@ -171,7 +171,7 @@
GsmSmsCbMessage.GeoFencingTriggerMessage triggerMessage =
GsmSmsCbMessage.createGeoFencingTriggerMessage(pdu);
- Log.d(TAG, "trigger message=" + triggerMessage);
+ Rlog.d(TAG, "trigger message=" + triggerMessage);
assertEquals(1, triggerMessage.type);
assertEquals(1, triggerMessage.cbIdentifiers.size());
@@ -1013,7 +1013,7 @@
@Test
public void testEtwsMessageNormal() {
SmsCbMessage msg = createFromPdu(etwsMessageNormal);
- Log.d(TAG, msg.toString());
+ Rlog.d(TAG, msg.toString());
assertEquals("GS mismatch", 0, msg.getGeographicalScope());
assertEquals("serial number mismatch", 0, msg.getSerialNumber());
assertEquals("message ID mismatch", 0x1100, msg.getServiceCategory());
@@ -1024,7 +1024,7 @@
@Test
public void testEtwsMessageCancel() {
SmsCbMessage msg = createFromPdu(etwsMessageCancel);
- Log.d(TAG, msg.toString());
+ Rlog.d(TAG, msg.toString());
assertEquals("GS mismatch", 0, msg.getGeographicalScope());
assertEquals("serial number mismatch", 0, msg.getSerialNumber());
assertEquals("message ID mismatch", 0x1100, msg.getServiceCategory());
@@ -1035,7 +1035,7 @@
@Test
public void testEtwsMessageTest() {
SmsCbMessage msg = createFromPdu(etwsMessageTest);
- Log.d(TAG, msg.toString());
+ Rlog.d(TAG, msg.toString());
assertEquals("GS mismatch", 0, msg.getGeographicalScope());
assertEquals("serial number mismatch", 0, msg.getSerialNumber());
assertEquals("message ID mismatch", 0x1103, msg.getServiceCategory());
@@ -1057,7 +1057,7 @@
// this should return a SmsCbMessage object or null for invalid data
SmsCbMessage msg = createFromPdu(data);
} catch (Exception e) {
- Log.d(TAG, "exception thrown", e);
+ Rlog.d(TAG, "exception thrown", e);
fail("Exception in decoder at run " + run + " length " + len + ": " + e);
}
}