下面列出了怎么用android.os.DropBoxManager的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Persisted recorder.
*/
public NetworkStatsRecorder(FileRotator rotator, NonMonotonicObserver<String> observer,
DropBoxManager dropBox, String cookie, long bucketDuration, boolean onlyTags) {
mRotator = checkNotNull(rotator, "missing FileRotator");
mObserver = checkNotNull(observer, "missing NonMonotonicObserver");
mDropBox = checkNotNull(dropBox, "missing DropBoxManager");
mCookie = cookie;
mBucketDuration = bucketDuration;
mOnlyTags = onlyTags;
mPending = new NetworkStatsCollection(bucketDuration);
mSinceBoot = new NetworkStatsCollection(bucketDuration);
mPendingRewriter = new CombiningRewriter(mPending);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
static DropBoxManager createDropBoxManager() {
IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
if (service == null) {
// Don't return a DropBoxManager that will NPE upon use.
// This also avoids caching a broken DropBoxManager in
// getDropBoxManager during early boot, before the
// DROPBOX_SERVICE is registered.
return null;
}
return new DropBoxManager(service);
}
WatchlistLoggingHandler(Context context, Looper looper) {
super(looper);
mContext = context;
mPm = mContext.getPackageManager();
mResolver = mContext.getContentResolver();
mDbHelper = WatchlistReportDbHelper.getInstance(context);
mConfig = WatchlistConfig.getInstance();
mSettings = WatchlistSettings.getInstance();
mDropBoxManager = mContext.getSystemService(DropBoxManager.class);
mPrimaryUserId = getPrimaryUserId();
}
private NetworkStatsRecorder buildRecorder(
String prefix, NetworkStatsSettings.Config config, boolean includeTags) {
final DropBoxManager dropBox = (DropBoxManager) mContext.getSystemService(
Context.DROPBOX_SERVICE);
return new NetworkStatsRecorder(new FileRotator(
mBaseDir, prefix, config.rotateAgeMillis, config.deleteAgeMillis),
mNonMonotonicObserver, dropBox, prefix, config.bucketDuration, includeTags);
}
@Override
public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
int rightIndex, String cookie) {
Log.w(TAG, "Found non-monotonic values; saving to dropbox");
// record error for debugging
final StringBuilder builder = new StringBuilder();
builder.append("found non-monotonic " + cookie + " values at left[" + leftIndex
+ "] - right[" + rightIndex + "]\n");
builder.append("left=").append(left).append('\n');
builder.append("right=").append(right).append('\n');
mContext.getSystemService(DropBoxManager.class).addText(TAG_NETSTATS_ERROR,
builder.toString());
}
@Override
public void foundNonMonotonic(
NetworkStats stats, int statsIndex, String cookie) {
Log.w(TAG, "Found non-monotonic values; saving to dropbox");
final StringBuilder builder = new StringBuilder();
builder.append("Found non-monotonic " + cookie + " values at [" + statsIndex + "]\n");
builder.append("stats=").append(stats).append('\n');
mContext.getSystemService(DropBoxManager.class).addText(TAG_NETSTATS_ERROR,
builder.toString());
}
/**
* Moves an existing temporary file to a new log filename.
*
* @param temp file to rename
* @param dir to store file in
* @param tag to use for new log file name
* @param timestampMillis of log entry
* @param flags for the entry data
* @param blockSize to use for space accounting
* @throws IOException if the file can't be moved
*/
public EntryFile(File temp, File dir, String tag,long timestampMillis,
int flags, int blockSize) throws IOException {
if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
this.tag = TextUtils.safeIntern(tag);
this.timestampMillis = timestampMillis;
this.flags = flags;
final File file = this.getFile(dir);
if (!temp.renameTo(file)) {
throw new IOException("Can't rename " + temp + " to " + file);
}
this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
}
/**
* Creates a EntryFile object with only a timestamp for comparison purposes.
* @param millis to compare with.
*/
public EntryFile(long millis) {
this.tag = null;
this.timestampMillis = millis;
this.flags = DropBoxManager.IS_EMPTY;
this.blocks = 0;
}
/** @return File extension for the flags. */
private String getExtension() {
if ((flags & DropBoxManager.IS_EMPTY) != 0) {
return ".lost";
}
return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
}
private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
if (!value.isNull()) {
return;
}
final int userId = getUserIdFromKey(secureSettings.mKey);
final UserInfo user;
final long identity = Binder.clearCallingIdentity();
try {
user = mUserManager.getUserInfo(userId);
} finally {
Binder.restoreCallingIdentity(identity);
}
if (user == null) {
// Can happen due to races when deleting users - treat as benign.
return;
}
String androidId = Long.toHexString(new SecureRandom().nextLong());
secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
+ "] for user " + userId);
// Write a drop box entry if it's a restricted profile
if (user.isRestricted()) {
DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
Context.DROPBOX_SERVICE);
if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
+ "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
}
}
}
@Override
public void add(DropBoxManager.Entry entry) {
DropBoxManagerService.this.add(entry);
}
@Override
public DropBoxManager.Entry getNextEntry(String tag, long millis) {
return DropBoxManagerService.this.getNextEntry(tag, millis);
}
/**
* Extracts metadata from an existing on-disk log filename.
*
* Note when a filename is not recognizable, it will create an instance that
* {@link #hasFile()} would return false on, and also remove the file.
*
* @param file name of existing log file
* @param blockSize to use for space accounting
*/
public EntryFile(File file, int blockSize) {
boolean parseFailure = false;
String name = file.getName();
int flags = 0;
String tag = null;
long millis = 0;
final int at = name.lastIndexOf('@');
if (at < 0) {
parseFailure = true;
} else {
tag = Uri.decode(name.substring(0, at));
if (name.endsWith(".gz")) {
flags |= DropBoxManager.IS_GZIPPED;
name = name.substring(0, name.length() - 3);
}
if (name.endsWith(".lost")) {
flags |= DropBoxManager.IS_EMPTY;
name = name.substring(at + 1, name.length() - 5);
} else if (name.endsWith(".txt")) {
flags |= DropBoxManager.IS_TEXT;
name = name.substring(at + 1, name.length() - 4);
} else if (name.endsWith(".dat")) {
name = name.substring(at + 1, name.length() - 4);
} else {
parseFailure = true;
}
if (!parseFailure) {
try {
millis = Long.parseLong(name);
} catch (NumberFormatException e) {
parseFailure = true;
}
}
}
if (parseFailure) {
Slog.wtf(TAG, "Invalid filename: " + file);
// Remove the file and return an empty instance.
file.delete();
this.tag = null;
this.flags = DropBoxManager.IS_EMPTY;
this.timestampMillis = 0;
this.blocks = 0;
return;
}
this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
this.tag = TextUtils.safeIntern(tag);
this.flags = flags;
this.timestampMillis = millis;
}
/** Moves a temporary file to a final log filename and enrolls it. */
private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
long t = System.currentTimeMillis();
// Require each entry to have a unique timestamp; if there are entries
// >10sec in the future (due to clock skew), drag them back to avoid
// keeping them around forever.
SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
EntryFile[] future = null;
if (!tail.isEmpty()) {
future = tail.toArray(new EntryFile[tail.size()]);
tail.clear(); // Remove from mAllFiles
}
if (!mAllFiles.contents.isEmpty()) {
t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
}
if (future != null) {
for (EntryFile late : future) {
mAllFiles.blocks -= late.blocks;
FileList tagFiles = mFilesByTag.get(late.tag);
if (tagFiles != null && tagFiles.contents.remove(late)) {
tagFiles.blocks -= late.blocks;
}
if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
late.tag, t++, late.flags, mBlockSize));
} else {
enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
}
}
}
if (temp == null) {
enrollEntry(new EntryFile(mDropBoxDir, tag, t));
} else {
enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
}
return t;
}
@Override
public DropBoxManager createService(ContextImpl ctx) throws ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(Context.DROPBOX_SERVICE);
IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
return new DropBoxManager(ctx, service);
}
@TargetApi(8)
public static DropBoxManager getDropBoxManager() {
return (DropBoxManager) getSystemService(Context.DROPBOX_SERVICE);
}
public void refreshDebugSettings() {
if (mECHelper != null && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
Object o = getSystemService(DROPBOX_SERVICE);
if (o != null) mECHelper.mDropBox = (DropBoxManager) o;
}
}
private boolean ensureAndroidIdIsSet(int userHandle) {
final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
new String[] { Settings.NameValueTable.VALUE },
Settings.NameValueTable.NAME + "=?",
new String[] { Settings.Secure.ANDROID_ID }, null,
userHandle);
try {
final String value = c.moveToNext() ? c.getString(0) : null;
if (value == null) {
// sanity-check the user before touching the db
final UserInfo user = mUserManager.getUserInfo(userHandle);
if (user == null) {
// can happen due to races when deleting users; treat as benign
return false;
}
final SecureRandom random = new SecureRandom();
final String newAndroidIdValue = Long.toHexString(random.nextLong());
final ContentValues values = new ContentValues();
values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
if (uri == null) {
Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
return false;
}
Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
+ "] for user " + userHandle);
// Write a dropbox entry if it's a restricted profile
if (user.isRestricted()) {
DropBoxManager dbm = (DropBoxManager)
getContext().getSystemService(Context.DROPBOX_SERVICE);
if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
+ ",restricted_profile_ssaid,"
+ newAndroidIdValue + "\n");
}
}
}
return true;
} finally {
c.close();
}
}
/**
* Creates a zero-length tombstone for a file whose contents were lost.
*
* @param dir to store file in
* @param tag to use for new log file name
* @param timestampMillis of log entry
* @throws IOException if the file can't be created.
*/
public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
this.tag = TextUtils.safeIntern(tag);
this.timestampMillis = timestampMillis;
this.flags = DropBoxManager.IS_EMPTY;
this.blocks = 0;
new FileOutputStream(getFile(dir)).close();
}