Java Examples for android.os.UserHandle

The following java examples will help you to understand the usage of android.os.UserHandle. These source code samples are taken from different open source projects.

Example 1
Project: KISS-master  File: LoadAppPojos.java View source code
@Override
protected ArrayList<AppPojo> doInBackground(Void... params) {
    long start = System.nanoTime();
    ArrayList<AppPojo> apps = new ArrayList<>();
    String excludedAppList = PreferenceManager.getDefaultSharedPreferences(context).getString("excluded-apps-list", context.getPackageName() + ";");
    List excludedApps = Arrays.asList(excludedAppList.split(";"));
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UserManager manager = (UserManager) context.getSystemService(Context.USER_SERVICE);
        LauncherApps launcher = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
        // Handle multi-profile support introduced in Android 5 (#542)
        for (android.os.UserHandle profile : manager.getUserProfiles()) {
            UserHandle user = new UserHandle(manager.getSerialNumberForUser(profile), profile);
            for (LauncherActivityInfo activityInfo : launcher.getActivityList(null, profile)) {
                ApplicationInfo appInfo = activityInfo.getApplicationInfo();
                String fullPackageName = user.addUserSuffixToString(appInfo.packageName, '#');
                if (!excludedApps.contains(fullPackageName)) {
                    AppPojo app = new AppPojo();
                    app.id = user.addUserSuffixToString(pojoScheme + appInfo.packageName + "/" + activityInfo.getName(), '/');
                    app.setName(activityInfo.getLabel().toString());
                    app.packageName = appInfo.packageName;
                    app.activityName = activityInfo.getName();
                    // Wrap Android user handle in opaque container that will work across
                    // all Android versions
                    app.userHandle = user;
                    app.setTags(tagsHandler.getTags(app.id));
                    apps.add(app);
                }
            }
        }
    } else {
        PackageManager manager = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        for (ResolveInfo info : manager.queryIntentActivities(mainIntent, 0)) {
            ApplicationInfo appInfo = info.activityInfo.applicationInfo;
            if (!excludedApps.contains(appInfo.packageName)) {
                AppPojo app = new AppPojo();
                app.id = pojoScheme + appInfo.packageName + "/" + info.activityInfo.name;
                app.setName(info.loadLabel(manager).toString());
                app.packageName = appInfo.packageName;
                app.activityName = info.activityInfo.name;
                app.userHandle = new UserHandle();
                app.setTags(tagsHandler.getTags(app.id));
                apps.add(app);
            }
        }
    }
    // Apply app sorting preference
    if (prefs.getString("sort-apps", "alphabetical").equals("invertedAlphabetical")) {
        Collections.sort(apps, Collections.reverseOrder(new AppPojo.NameComparator()));
    } else {
        Collections.sort(apps, new AppPojo.NameComparator());
    }
    long end = System.nanoTime();
    Log.i("time", Long.toString((end - start) / 1000000) + " milliseconds to list apps");
    return apps;
}
Example 2
Project: android-sdk-sources-for-api-level-23-master  File: PhoneStatusBar.java View source code
// ================================================================================
// Constructing the view
// ================================================================================
protected PhoneStatusBarView makeStatusBarView() {
    final Context context = mContext;
    Resources res = context.getResources();
    // populates mDisplayMetrics
    updateDisplaySize();
    updateResources();
    mStatusBarWindow = (StatusBarWindowView) View.inflate(context, R.layout.super_status_bar, null);
    mStatusBarWindow.setService(this);
    mStatusBarWindow.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            checkUserAutohide(v, event);
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (mExpandedVisible) {
                    animateCollapsePanels();
                }
            }
            return mStatusBarWindow.onTouchEvent(event);
        }
    });
    mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
    mStatusBarView.setBar(this);
    PanelHolder holder = (PanelHolder) mStatusBarWindow.findViewById(R.id.panel_holder);
    mStatusBarView.setPanelHolder(holder);
    mNotificationPanel = (NotificationPanelView) mStatusBarWindow.findViewById(R.id.notification_panel);
    mNotificationPanel.setStatusBar(this);
    if (!ActivityManager.isHighEndGfx()) {
        mStatusBarWindow.setBackground(null);
        mNotificationPanel.setBackground(new FastColorDrawable(context.getColor(R.color.notification_panel_solid_background)));
    }
    mHeadsUpManager = new HeadsUpManager(context, mStatusBarWindow);
    mHeadsUpManager.setBar(this);
    mHeadsUpManager.addListener(this);
    mHeadsUpManager.addListener(mNotificationPanel);
    mNotificationPanel.setHeadsUpManager(mHeadsUpManager);
    mNotificationData.setHeadsUpManager(mHeadsUpManager);
    if (MULTIUSER_DEBUG) {
        mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(R.id.header_debug_info);
        mNotificationPanelDebugText.setVisibility(View.VISIBLE);
    }
    try {
        boolean showNav = mWindowManagerService.hasNavigationBar();
        if (DEBUG)
            Log.v(TAG, "hasNavigationBar=" + showNav);
        if (showNav) {
            mNavigationBarView = (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
            mNavigationBarView.setDisabledFlags(mDisabled1);
            mNavigationBarView.setBar(this);
            mNavigationBarView.setOnVerticalChangedListener(new NavigationBarView.OnVerticalChangedListener() {

                @Override
                public void onVerticalChanged(boolean isVertical) {
                    if (mAssistManager != null) {
                        mAssistManager.onConfigurationChanged();
                    }
                    mNotificationPanel.setQsScrimEnabled(!isVertical);
                }
            });
            mNavigationBarView.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    checkUserAutohide(v, event);
                    return false;
                }
            });
        }
    } catch (RemoteException ex) {
    }
    mAssistManager = new AssistManager(this, context);
    // figure out which pixel-format to use for the status bar.
    mPixelFormat = PixelFormat.OPAQUE;
    mStackScroller = (NotificationStackScrollLayout) mStatusBarWindow.findViewById(R.id.notification_stack_scroller);
    mStackScroller.setLongPressListener(getNotificationLongClicker());
    mStackScroller.setPhoneStatusBar(this);
    mStackScroller.setGroupManager(mGroupManager);
    mStackScroller.setHeadsUpManager(mHeadsUpManager);
    mGroupManager.setOnGroupChangeListener(mStackScroller);
    mKeyguardIconOverflowContainer = (NotificationOverflowContainer) LayoutInflater.from(mContext).inflate(R.layout.status_bar_notification_keyguard_overflow, mStackScroller, false);
    mKeyguardIconOverflowContainer.setOnActivatedListener(this);
    mKeyguardIconOverflowContainer.setOnClickListener(mOverflowClickListener);
    mStackScroller.setOverflowContainer(mKeyguardIconOverflowContainer);
    SpeedBumpView speedBump = (SpeedBumpView) LayoutInflater.from(mContext).inflate(R.layout.status_bar_notification_speed_bump, mStackScroller, false);
    mStackScroller.setSpeedBumpView(speedBump);
    mEmptyShadeView = (EmptyShadeView) LayoutInflater.from(mContext).inflate(R.layout.status_bar_no_notifications, mStackScroller, false);
    mStackScroller.setEmptyShadeView(mEmptyShadeView);
    mDismissView = (DismissView) LayoutInflater.from(mContext).inflate(R.layout.status_bar_notification_dismiss_all, mStackScroller, false);
    mDismissView.setOnButtonClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MetricsLogger.action(mContext, MetricsLogger.ACTION_DISMISS_ALL_NOTES);
            clearAllNotifications();
        }
    });
    mStackScroller.setDismissView(mDismissView);
    mExpandedContents = mStackScroller;
    mBackdrop = (BackDropView) mStatusBarWindow.findViewById(R.id.backdrop);
    mBackdropFront = (ImageView) mBackdrop.findViewById(R.id.backdrop_front);
    mBackdropBack = (ImageView) mBackdrop.findViewById(R.id.backdrop_back);
    ScrimView scrimBehind = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_behind);
    ScrimView scrimInFront = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_in_front);
    View headsUpScrim = mStatusBarWindow.findViewById(R.id.heads_up_scrim);
    mScrimController = new ScrimController(scrimBehind, scrimInFront, headsUpScrim, mScrimSrcModeEnabled);
    mHeadsUpManager.addListener(mScrimController);
    mStackScroller.setScrimController(mScrimController);
    mScrimController.setBackDropView(mBackdrop);
    mStatusBarView.setScrimController(mScrimController);
    mDozeScrimController = new DozeScrimController(mScrimController, context);
    mHeader = (StatusBarHeaderView) mStatusBarWindow.findViewById(R.id.header);
    mHeader.setActivityStarter(this);
    mKeyguardStatusBar = (KeyguardStatusBarView) mStatusBarWindow.findViewById(R.id.keyguard_header);
    mKeyguardStatusView = mStatusBarWindow.findViewById(R.id.keyguard_status_view);
    mKeyguardBottomArea = (KeyguardBottomAreaView) mStatusBarWindow.findViewById(R.id.keyguard_bottom_area);
    mKeyguardBottomArea.setActivityStarter(this);
    mKeyguardBottomArea.setAssistManager(mAssistManager);
    mKeyguardIndicationController = new KeyguardIndicationController(mContext, (KeyguardIndicationTextView) mStatusBarWindow.findViewById(R.id.keyguard_indication_text));
    mKeyguardBottomArea.setKeyguardIndicationController(mKeyguardIndicationController);
    // set the inital view visibility
    setAreThereNotifications();
    mIconController = new StatusBarIconController(mContext, mStatusBarView, mKeyguardStatusBar, this);
    // Background thread for any controllers that need it.
    mHandlerThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();
    // Other icons
    mLocationController = new LocationControllerImpl(mContext, // will post a notification
    mHandlerThread.getLooper());
    mBatteryController = new BatteryController(mContext);
    mBatteryController.addStateChangedCallback(new BatteryStateChangeCallback() {

        @Override
        public void onPowerSaveChanged() {
            mHandler.post(mCheckBarModes);
            if (mDozeServiceHost != null) {
                mDozeServiceHost.firePowerSaveChanged(mBatteryController.isPowerSave());
            }
        }

        @Override
        public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
        // noop
        }
    });
    mNetworkController = new NetworkControllerImpl(mContext, mHandlerThread.getLooper());
    mHotspotController = new HotspotControllerImpl(mContext);
    mBluetoothController = new BluetoothControllerImpl(mContext, mHandlerThread.getLooper());
    mSecurityController = new SecurityControllerImpl(mContext);
    if (mContext.getResources().getBoolean(R.bool.config_showRotationLock)) {
        mRotationLockController = new RotationLockControllerImpl(mContext);
    }
    mUserInfoController = new UserInfoController(mContext);
    mVolumeComponent = getComponent(VolumeComponent.class);
    if (mVolumeComponent != null) {
        mZenModeController = mVolumeComponent.getZenController();
    }
    mCastController = new CastControllerImpl(mContext);
    final SignalClusterView signalCluster = (SignalClusterView) mStatusBarView.findViewById(R.id.signal_cluster);
    final SignalClusterView signalClusterKeyguard = (SignalClusterView) mKeyguardStatusBar.findViewById(R.id.signal_cluster);
    final SignalClusterView signalClusterQs = (SignalClusterView) mHeader.findViewById(R.id.signal_cluster);
    mNetworkController.addSignalCallback(signalCluster);
    mNetworkController.addSignalCallback(signalClusterKeyguard);
    mNetworkController.addSignalCallback(signalClusterQs);
    signalCluster.setSecurityController(mSecurityController);
    signalCluster.setNetworkController(mNetworkController);
    signalClusterKeyguard.setSecurityController(mSecurityController);
    signalClusterKeyguard.setNetworkController(mNetworkController);
    signalClusterQs.setSecurityController(mSecurityController);
    signalClusterQs.setNetworkController(mNetworkController);
    final boolean isAPhone = mNetworkController.hasVoiceCallingFeature();
    if (isAPhone) {
        mNetworkController.addEmergencyListener(mHeader);
    }
    mFlashlightController = new FlashlightController(mContext);
    mKeyguardBottomArea.setFlashlightController(mFlashlightController);
    mKeyguardBottomArea.setPhoneStatusBar(this);
    mKeyguardBottomArea.setUserSetupComplete(mUserSetup);
    mAccessibilityController = new AccessibilityController(mContext);
    mKeyguardBottomArea.setAccessibilityController(mAccessibilityController);
    mNextAlarmController = new NextAlarmController(mContext);
    mKeyguardMonitor = new KeyguardMonitor(mContext);
    if (UserSwitcherController.isUserSwitcherAvailable(UserManager.get(mContext))) {
        mUserSwitcherController = new UserSwitcherController(mContext, mKeyguardMonitor, mHandler);
    }
    mKeyguardUserSwitcher = new KeyguardUserSwitcher(mContext, (ViewStub) mStatusBarWindow.findViewById(R.id.keyguard_user_switcher), mKeyguardStatusBar, mNotificationPanel, mUserSwitcherController);
    // Set up the quick settings tile panel
    mQSPanel = (QSPanel) mStatusBarWindow.findViewById(R.id.quick_settings_panel);
    if (mQSPanel != null) {
        final QSTileHost qsh = new QSTileHost(mContext, this, mBluetoothController, mLocationController, mRotationLockController, mNetworkController, mZenModeController, mHotspotController, mCastController, mFlashlightController, mUserSwitcherController, mKeyguardMonitor, mSecurityController);
        mQSPanel.setHost(qsh);
        mQSPanel.setTiles(qsh.getTiles());
        mBrightnessMirrorController = new BrightnessMirrorController(mStatusBarWindow);
        mQSPanel.setBrightnessMirror(mBrightnessMirrorController);
        mHeader.setQSPanel(mQSPanel);
        qsh.setCallback(new QSTileHost.Callback() {

            @Override
            public void onTilesChanged() {
                mQSPanel.setTiles(qsh.getTiles());
            }
        });
    }
    // User info. Trigger first load.
    mHeader.setUserInfoController(mUserInfoController);
    mKeyguardStatusBar.setUserInfoController(mUserInfoController);
    mKeyguardStatusBar.setUserSwitcherController(mUserSwitcherController);
    mUserInfoController.reloadUserInfo();
    mHeader.setBatteryController(mBatteryController);
    ((BatteryMeterView) mStatusBarView.findViewById(R.id.battery)).setBatteryController(mBatteryController);
    mKeyguardStatusBar.setBatteryController(mBatteryController);
    mHeader.setNextAlarmController(mNextAlarmController);
    PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    mBroadcastReceiver.onReceive(mContext, new Intent(pm.isScreenOn() ? Intent.ACTION_SCREEN_ON : Intent.ACTION_SCREEN_OFF));
    // receive broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    context.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
    IntentFilter demoFilter = new IntentFilter();
    if (DEBUG_MEDIA_FAKE_ARTWORK) {
        demoFilter.addAction(ACTION_FAKE_ARTWORK);
    }
    demoFilter.addAction(ACTION_DEMO);
    context.registerReceiverAsUser(mDemoReceiver, UserHandle.ALL, demoFilter, android.Manifest.permission.DUMP, null);
    // listen for USER_SETUP_COMPLETE setting (per-user)
    resetUserSetupObserver();
    // disable profiling bars, since they overlap and clutter the output on app windows
    ThreadedRenderer.overrideProperty("disableProfileBars", "true");
    // Private API call to make the shadows look better for Recents
    ThreadedRenderer.overrideProperty("ambientRatio", String.valueOf(1.5f));
    return mStatusBarView;
}
Example 3
Project: android-testdpc-master  File: PolicyManagementFragment.java View source code
@Override
public void onClick(DialogInterface dialogInterface, int i) {
    String name = userNameEditText.getText().toString();
    if (!TextUtils.isEmpty(name)) {
        int flags = skipSetupWizardCheckBox.isChecked() ? DevicePolicyManager.SKIP_SETUP_WIZARD : 0;
        UserHandle userHandle = mDevicePolicyManager.createAndManageUser(mAdminComponentName, name, mAdminComponentName, null, flags);
        if (userHandle != null) {
            long serialNumber = mUserManager.getSerialNumberForUser(userHandle);
            showToast(R.string.user_created, serialNumber);
            return;
        }
        showToast(R.string.failed_to_create_user);
    }
}
Example 4
Project: AndroidN-ify-master  File: LiveDisplayObserver.java View source code
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
    Context context = (Context) XposedHelpers.getObjectField(param.thisObject, "mContext");
    mCurrentMode = (Integer) XposedHelpers.callMethod(param.thisObject, "getCurrentModeIndex");
    Intent intent = new Intent(LIVE_DISPLAY_MODE_CHANGED).putExtra(EXTRA_LIVE_DISPLAY_MODE, mCurrentMode);
    context.sendBroadcastAsUser(intent, (UserHandle) XposedHelpers.getStaticObjectField(UserHandle.class, "CURRENT"));
}
Example 5
Project: android_frameworks_base-master  File: ShortcutManagerTest1.java View source code
public void testSetDynamicShortcuts() {
    setCaller(CALLING_PACKAGE_1, USER_0);
    final Icon icon1 = Icon.createWithResource(getTestContext(), R.drawable.icon1);
    final Icon icon2 = Icon.createWithBitmap(BitmapFactory.decodeResource(getTestContext().getResources(), R.drawable.icon2));
    final ShortcutInfo si1 = makeShortcut("shortcut1", "Title 1", makeComponent(ShortcutActivity.class), icon1, makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class, "key1", "val1", "nest", makeBundle("key", 123)), /* weight */
    10);
    final ShortcutInfo si2 = makeShortcut("shortcut2", "Title 2", /* activity */
    null, icon2, makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class), /* weight */
    12);
    final ShortcutInfo si3 = makeShortcut("shortcut3");
    assertTrue(mManager.setDynamicShortcuts(list(si1, si2)));
    assertShortcutIds(assertAllNotKeyFieldsOnly(mManager.getDynamicShortcuts()), "shortcut1", "shortcut2");
    assertEquals(2, mManager.getRemainingCallCount());
    // TODO: Check fields
    assertTrue(mManager.setDynamicShortcuts(list(si1)));
    assertShortcutIds(assertAllNotKeyFieldsOnly(mManager.getDynamicShortcuts()), "shortcut1");
    assertEquals(1, mManager.getRemainingCallCount());
    assertTrue(mManager.setDynamicShortcuts(list()));
    assertEquals(0, mManager.getDynamicShortcuts().size());
    assertEquals(0, mManager.getRemainingCallCount());
    dumpsysOnLogcat();
    // Need to advance the clock for reset to work.
    mInjectedCurrentTimeMillis++;
    mService.resetThrottlingInner(UserHandle.USER_SYSTEM);
    dumpsysOnLogcat();
    assertTrue(mManager.setDynamicShortcuts(list(si2, si3)));
    assertEquals(2, mManager.getDynamicShortcuts().size());
    // TODO Check max number
    mRunningUsers.put(USER_10, true);
    runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
        assertTrue(mManager.setDynamicShortcuts(list(makeShortcut("s1"))));
    });
}
Example 6
Project: android_packages_apps_Bluetooth-master  File: HeadsetStateMachine.java View source code
// This method does not check for error conditon (newState == prevState)
private void broadcastConnectionState(BluetoothDevice device, int newState, int prevState) {
    if (DBG)
        Log.d(TAG, "Enter broadcastConnectionState()");
    if (DBG)
        Log.d(TAG, "Connection state " + device + ": " + prevState + "->" + newState);
    if (prevState == BluetoothProfile.STATE_CONNECTED) {
        // Headset is disconnecting, stop Virtual call if active.
        terminateScoUsingVirtualVoiceCall();
    }
    /* Notifying the connection state change of the profile before sending the intent for
           connection state change, as it was causing a race condition, with the UI not being
           updated with the correct connection state. */
    mService.notifyProfileConnectionStateChanged(device, BluetoothProfile.HEADSET, newState, prevState);
    Intent intent = new Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
    intent.putExtra(BluetoothProfile.EXTRA_STATE, newState);
    intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
    mService.sendBroadcastAsUser(intent, UserHandle.ALL, HeadsetService.BLUETOOTH_PERM);
    if (DBG)
        Log.d(TAG, "Exit broadcastConnectionState()");
}
Example 7
Project: Appsii-master  File: AppWidgetManagerCompatVL.java View source code
@Override
public List<AppWidgetProviderInfo> getAllProviders() {
    ArrayList<AppWidgetProviderInfo> providers = new ArrayList<AppWidgetProviderInfo>();
    List<UserHandle> userProfiles = mUserManager.getUserProfiles();
    int N = userProfiles.size();
    for (int i = 0; i < N; i++) {
        UserHandle user = userProfiles.get(i);
        providers.addAll(mAppWidgetManager.getInstalledProvidersForProfile(user));
    }
    return providers;
}
Example 8
Project: ify-master  File: LiveDisplayObserver.java View source code
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
    Context context = (Context) XposedHelpers.getObjectField(param.thisObject, "mContext");
    mCurrentMode = (Integer) XposedHelpers.callMethod(param.thisObject, "getCurrentModeIndex");
    Intent intent = new Intent(LIVE_DISPLAY_MODE_CHANGED).putExtra(EXTRA_LIVE_DISPLAY_MODE, mCurrentMode);
    context.sendBroadcastAsUser(intent, (UserHandle) XposedHelpers.getStaticObjectField(UserHandle.class, "CURRENT"));
}
Example 9
Project: packages_apps_OneStep-master  File: Utils.java View source code
public static void launchPreviousApp(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(2, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
    if (recentTasks.size() >= 2) {
        int taskId = recentTasks.get(1).id;
        if (taskId >= 0) {
            am.moveTaskToFront(taskId, ActivityManager.MOVE_TASK_WITH_HOME);
        } else {
            Intent intent = new Intent(recentTasks.get(1).baseIntent);
            if (intent != null && intent.getComponent() != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY | Intent.FLAG_ACTIVITY_TASK_ON_HOME | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivityAsUser(intent, UserHandle.CURRENT);
            }
        }
    }
}
Example 10
Project: packages_apps_settings-master  File: DevelopmentSettings.java View source code
private void writeWebViewMultiprocessOptions() {
    boolean value = mWebViewMultiprocess.isChecked();
    Settings.Global.putInt(getActivity().getContentResolver(), Settings.Global.WEBVIEW_MULTIPROCESS, value ? 1 : 0);
    try {
        String wv_package = mWebViewUpdateService.getCurrentWebViewPackageName();
        ActivityManagerNative.getDefault().killPackageDependents(wv_package, UserHandle.USER_ALL);
    } catch (RemoteException e) {
    }
}
Example 11
Project: platform_frameworks_base-master  File: WifiConfiguration.java View source code
/** @hide
     *  return the string used to calculate the hash in WifiConfigStore
     *  and uniquely identify this WifiConfiguration
     */
public String configKey(boolean allowCached) {
    String key;
    if (allowCached && mCachedConfigKey != null) {
        key = mCachedConfigKey;
    } else if (providerFriendlyName != null) {
        key = FQDN + KeyMgmt.strings[KeyMgmt.WPA_EAP];
        if (!shared) {
            key += "-" + Integer.toString(UserHandle.getUserId(creatorUid));
        }
    } else {
        if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
            key = SSID + KeyMgmt.strings[KeyMgmt.WPA_PSK];
        } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP) || allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
            key = SSID + KeyMgmt.strings[KeyMgmt.WPA_EAP];
        } else if (wepKeys[0] != null) {
            key = SSID + "WEP";
        } else {
            key = SSID + KeyMgmt.strings[KeyMgmt.NONE];
        }
        if (!shared) {
            key += "-" + Integer.toString(UserHandle.getUserId(creatorUid));
        }
        mCachedConfigKey = key;
    }
    return key;
}
Example 12
Project: platform_packages_apps_settings-master  File: DevelopmentSettings.java View source code
private void writeWebViewMultiprocessOptions() {
    boolean value = mWebViewMultiprocess.isChecked();
    Settings.Global.putInt(getActivity().getContentResolver(), Settings.Global.WEBVIEW_MULTIPROCESS, value ? 1 : 0);
    try {
        String wv_package = mWebViewUpdateService.getCurrentWebViewPackageName();
        ActivityManagerNative.getDefault().killPackageDependents(wv_package, UserHandle.USER_ALL);
    } catch (RemoteException e) {
    }
}
Example 13
Project: property-db-master  File: PhoneStatusBar.java View source code
public void startActivityDismissingKeyguard(Intent intent, boolean onlyProvisioned) {
    if (onlyProvisioned && !isDeviceProvisioned())
        return;
    try {
        // Dismiss the lock screen when Settings starts.
        ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
    } catch (RemoteException e) {
    }
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
    animateCollapsePanels();
}
Example 14
Project: SNLauncher-master  File: UserManagerCompatVL.java View source code
@Override
public List<UserHandleCompat> getUserProfiles() {
    List<UserHandle> users = mUserManager.getUserProfiles();
    if (users == null) {
        return Collections.EMPTY_LIST;
    }
    ArrayList<UserHandleCompat> compatUsers = new ArrayList<UserHandleCompat>(users.size());
    for (UserHandle user : users) {
        compatUsers.add(UserHandleCompat.fromUser(user));
    }
    return compatUsers;
}
Example 15
Project: WallpaperPicker-master  File: UserManagerCompatVL.java View source code
@Override
public List<UserHandleCompat> getUserProfiles() {
    List<UserHandle> users = mUserManager.getUserProfiles();
    if (users == null) {
        return Collections.EMPTY_LIST;
    }
    ArrayList<UserHandleCompat> compatUsers = new ArrayList<UserHandleCompat>(users.size());
    for (UserHandle user : users) {
        compatUsers.add(UserHandleCompat.fromUser(user));
    }
    return compatUsers;
}
Example 16
Project: android_device_softwinner_cubieboard1-master  File: DataUsageSummary.java View source code
@Override
public void onPrepareOptionsMenu(Menu menu) {
    final Context context = getActivity();
    final boolean appDetailMode = isAppDetailMode();
    final boolean isOwner = ActivityManager.getCurrentUser() == UserHandle.USER_OWNER;
    mMenuDataRoaming = menu.findItem(R.id.data_usage_menu_roaming);
    mMenuDataRoaming.setVisible(hasReadyMobileRadio(context) && !appDetailMode);
    mMenuDataRoaming.setChecked(getDataRoaming());
    mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
    mMenuRestrictBackground.setVisible(hasReadyMobileRadio(context) && !appDetailMode);
    mMenuRestrictBackground.setChecked(mPolicyManager.getRestrictBackground());
    mMenuRestrictBackground.setVisible(isOwner);
    mMenuAutoSync = menu.findItem(R.id.data_usage_menu_auto_sync);
    mMenuAutoSync.setChecked(ContentResolver.getMasterSyncAutomatically());
    mMenuAutoSync.setVisible(!appDetailMode);
    final MenuItem split4g = menu.findItem(R.id.data_usage_menu_split_4g);
    split4g.setVisible(hasReadyMobile4gRadio(context) && isOwner && !appDetailMode);
    split4g.setChecked(isMobilePolicySplit());
    final MenuItem showWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
    if (hasWifiRadio(context) && hasReadyMobileRadio(context)) {
        showWifi.setVisible(!appDetailMode);
        showWifi.setChecked(mShowWifi);
    } else {
        showWifi.setVisible(false);
    }
    final MenuItem showEthernet = menu.findItem(R.id.data_usage_menu_show_ethernet);
    if (hasEthernet(context) && hasReadyMobileRadio(context)) {
        showEthernet.setVisible(!appDetailMode);
        showEthernet.setChecked(mShowEthernet);
    } else {
        showEthernet.setVisible(false);
    }
    final MenuItem metered = menu.findItem(R.id.data_usage_menu_metered);
    if (hasReadyMobileRadio(context) || hasWifiRadio(context)) {
        metered.setVisible(!appDetailMode);
    } else {
        metered.setVisible(false);
    }
    final MenuItem help = menu.findItem(R.id.data_usage_menu_help);
    String helpUrl;
    if (!TextUtils.isEmpty(helpUrl = getResources().getString(R.string.help_url_data_usage))) {
        Intent helpIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
        helpIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        help.setIntent(helpIntent);
        help.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
    } else {
        help.setVisible(false);
    }
}
Example 17
Project: FlickLauncher-master  File: Launcher.java View source code
// TODO: These method should be a part of LauncherSearchCallback
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
    // Called from search suggestion
    UserHandleCompat user = null;
    if (Utilities.ATLEAST_LOLLIPOP) {
        UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
        if (userHandle != null) {
            user = UserHandleCompat.fromUser(userHandle);
        }
    }
    return createAppDragInfo(appLaunchIntent, user);
}
Example 18
Project: homescreen-master  File: Launcher.java View source code
// TODO: These method should be a part of LauncherSearchCallback
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
    // Called from search suggestion
    UserHandleCompat user = null;
    if (Utilities.ATLEAST_LOLLIPOP) {
        UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
        if (userHandle != null) {
            user = UserHandleCompat.fromUser(userHandle);
        }
    }
    return createAppDragInfo(appLaunchIntent, user);
}
Example 19
Project: nitrogen-master  File: SmartbarSettings.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.smartbar_settings);
    int contextVal = Settings.Secure.getIntForUser(getContentResolver(), "smartbar_context_menu_mode", 0, UserHandle.USER_CURRENT);
    mSmartBarContext = (ListPreference) findPreference("smartbar_context_menu_position");
    mSmartBarContext.setValue(String.valueOf(contextVal));
    mSmartBarContext.setOnPreferenceChangeListener(this);
    int imeVal = Settings.Secure.getIntForUser(getContentResolver(), "smartbar_ime_hint_mode", 1, UserHandle.USER_CURRENT);
    mImeActions = (ListPreference) findPreference("smartbar_ime_action");
    mImeActions.setValue(String.valueOf(imeVal));
    mImeActions.setOnPreferenceChangeListener(this);
    int buttonAnimVal = Settings.Secure.getIntForUser(getContentResolver(), "smartbar_button_animation_style", 0, UserHandle.USER_CURRENT);
    mButtonAnim = (ListPreference) findPreference("smartbar_button_animation");
    mButtonAnim.setValue(String.valueOf(buttonAnimVal));
    mButtonAnim.setOnPreferenceChangeListener(this);
    mButtonsAlpha = (CustomSeekBarPreference) findPreference(PREF_NAVBAR_BUTTONS_ALPHA);
    int bAlpha = Settings.Secure.getIntForUser(getContentResolver(), Settings.Secure.NAVBAR_BUTTONS_ALPHA, 255, UserHandle.USER_CURRENT);
    mButtonsAlpha.setValue(bAlpha / 1);
    mButtonsAlpha.setOnPreferenceChangeListener(this);
    setHasOptionsMenu(true);
}
Example 20
Project: Project-M-1-master  File: DataUsageSummary.java View source code
@Override
public void onPrepareOptionsMenu(Menu menu) {
    final Context context = getActivity();
    final boolean appDetailMode = isAppDetailMode();
    final boolean isOwner = ActivityManager.getCurrentUser() == UserHandle.USER_OWNER;
    mMenuDataRoaming = menu.findItem(R.id.data_usage_menu_roaming);
    mMenuDataRoaming.setVisible(hasReadyMobileRadio(context) && !appDetailMode);
    mMenuDataRoaming.setChecked(getDataRoaming());
    mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
    mMenuRestrictBackground.setVisible(hasReadyMobileRadio(context) && !appDetailMode);
    mMenuRestrictBackground.setChecked(mPolicyManager.getRestrictBackground());
    mMenuRestrictBackground.setVisible(isOwner);
    mMenuAutoSync = menu.findItem(R.id.data_usage_menu_auto_sync);
    mMenuAutoSync.setChecked(ContentResolver.getMasterSyncAutomatically());
    mMenuAutoSync.setVisible(!appDetailMode);
    final MenuItem split4g = menu.findItem(R.id.data_usage_menu_split_4g);
    split4g.setVisible(hasReadyMobile4gRadio(context) && isOwner && !appDetailMode);
    split4g.setChecked(isMobilePolicySplit());
    final MenuItem showWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
    if (hasWifiRadio(context) && hasReadyMobileRadio(context)) {
        showWifi.setVisible(!appDetailMode);
        showWifi.setChecked(mShowWifi);
    } else {
        showWifi.setVisible(false);
    }
    final MenuItem showEthernet = menu.findItem(R.id.data_usage_menu_show_ethernet);
    if (hasEthernet(context) && hasReadyMobileRadio(context)) {
        showEthernet.setVisible(!appDetailMode);
        showEthernet.setChecked(mShowEthernet);
    } else {
        showEthernet.setVisible(false);
    }
    final MenuItem metered = menu.findItem(R.id.data_usage_menu_metered);
    if (hasReadyMobileRadio(context) || hasWifiRadio(context)) {
        metered.setVisible(!appDetailMode);
    } else {
        metered.setVisible(false);
    }
    final MenuItem help = menu.findItem(R.id.data_usage_menu_help);
    String helpUrl;
    if (!TextUtils.isEmpty(helpUrl = getResources().getString(R.string.help_url_data_usage))) {
        HelpUtils.prepareHelpMenuItem(context, help, helpUrl);
    } else {
        help.setVisible(false);
    }
}
Example 21
Project: tabletkat-master  File: BaseStatusBarMod.java View source code
@Override
protected Object replaceHookedMethod(MethodHookParam methodHookParam) throws Throwable {
    if (!mIsTv || self == null) {
        return null;
    }
    IBinder key = (IBinder) methodHookParam.args[0];
    StatusBarNotification notification = (StatusBarNotification) methodHookParam.args[1];
    Object mInterruptingNotificationEntry = XposedHelpers.getObjectField(self, "mInterruptingNotificationEntry");
    mRecentsPreloadOnTouchListener = (View.OnTouchListener) XposedHelpers.getObjectField(self, "mRecentsPreloadOnTouchListener");
    mPile = (ViewGroup) XposedHelpers.getObjectField(self, "mPile");
    if (DEBUG)
        Log.d(TAG, "updateNotification(" + key + " -> " + notification + ")");
    final Object oldEntry = XposedHelpers.callMethod(mNotificationData, "findByKey", key);
    if (oldEntry == null) {
        Log.w(TAG, "updateNotification for unknown key: " + key);
        return null;
    }
    final StatusBarNotification oldNotification = (StatusBarNotification) XposedHelpers.getObjectField(oldEntry, "notification");
    // XXX: modify when we do something more intelligent with the two content views
    final RemoteViews oldContentView = oldNotification.getNotification().contentView;
    final RemoteViews contentView = notification.getNotification().contentView;
    final RemoteViews oldBigContentView = oldNotification.getNotification().bigContentView;
    final RemoteViews bigContentView = notification.getNotification().bigContentView;
    Object row = XposedHelpers.getObjectField(oldEntry, "row");
    if (DEBUG) {
        Object parent = XposedHelpers.callMethod(row, "getParent");
        Log.d(TAG, "old notification: when=" + oldNotification.getNotification().when + " ongoing=" + oldNotification.isOngoing() + " expanded=" + XposedHelpers.getObjectField(oldEntry, "expanded") + " contentView=" + oldContentView + " bigContentView=" + oldBigContentView + " rowParent=" + parent);
        Log.d(TAG, "new notification: when=" + notification.getNotification().when + " ongoing=" + oldNotification.isOngoing() + " contentView=" + contentView + " bigContentView=" + bigContentView);
    }
    // Can we just reapply the RemoteViews in place?  If when didn't change, the order
    // didn't change.
    // 1U is never null
    boolean contentsUnchanged = (XposedHelpers.getObjectField(oldEntry, "expanded") != null && contentView.getPackage() != null && oldContentView.getPackage() != null && oldContentView.getPackage().equals(contentView.getPackage()) && oldContentView.getLayoutId() == contentView.getLayoutId());
    // large view may be null
    boolean bigContentsUnchanged = (XposedHelpers.callMethod(oldEntry, "getBigContentView") == null && bigContentView == null) || ((XposedHelpers.callMethod(oldEntry, "getBigContentView") != null && bigContentView != null) && bigContentView.getPackage() != null && oldBigContentView.getPackage() != null && oldBigContentView.getPackage().equals(bigContentView.getPackage()) && oldBigContentView.getLayoutId() == bigContentView.getLayoutId());
    ViewGroup rowParent = (ViewGroup) XposedHelpers.callMethod(row, "getParent");
    int notificationScore = (Integer) XposedHelpers.callMethod(notification, "getScore");
    int oldNotificationScore = (Integer) XposedHelpers.callMethod(oldNotification, "getScore");
    boolean orderUnchanged = notification.getNotification().when == oldNotification.getNotification().when && notificationScore == oldNotificationScore;
    // score now encompasses/supersedes isOngoing()
    StatusBarNotification s = (StatusBarNotification) XposedHelpers.getObjectField(oldEntry, "notification");
    boolean updateTicker = notification.getNotification().tickerText != null && !TextUtils.equals(notification.getNotification().tickerText, s.getNotification().tickerText);
    boolean isTopAnyway = (Boolean) XposedHelpers.callMethod(self, "isTopNotification", rowParent, oldEntry);
    if (contentsUnchanged && bigContentsUnchanged && (orderUnchanged || isTopAnyway)) {
        if (DEBUG)
            Log.d(TAG, "reusing notification for key: " + key);
        XposedHelpers.setObjectField(oldEntry, "notification", notification);
        try {
            updateNotificationViews(oldEntry, notification);
            if (ENABLE_HEADS_UP && mInterruptingNotificationEntry != null && oldNotification == XposedHelpers.getObjectField(mInterruptingNotificationEntry, "notification")) {
                if (!(Boolean) XposedHelpers.callMethod(self, "shouldInterrupt", notification)) {
                    if (DEBUG)
                        Log.d(TAG, "no longer interrupts!");
                    mHandler.sendEmptyMessage(MSG_HIDE_HEADS_UP);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "updating the current heads up:" + notification);
                    XposedHelpers.setObjectField(mInterruptingNotificationEntry, "notification", notification);
                    updateNotificationViews(mInterruptingNotificationEntry, notification);
                }
            }
            // Update the icon.
            final Parcelable ic = (Parcelable) XposedHelpers.newInstance(TabletKatModule.mStatusBarIconClass, notification.getPackageName(), (UserHandle) XposedHelpers.callMethod(notification, "getUser"), notification.getNotification().icon, notification.getNotification().iconLevel, notification.getNotification().number, notification.getNotification().tickerText);
            Object icon = XposedHelpers.getObjectField(oldEntry, "icon");
            if (!(Boolean) XposedHelpers.callMethod(icon, "set", ic)) {
                XposedHelpers.callMethod(self, "handleNotificationError", key, notification, "Couldn't update icon: " + ic);
                return null;
            }
            XposedHelpers.callMethod(self, "updateExpansionStates");
            updatePeek(key);
        } catch (RuntimeException e) {
            Log.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
            removeNotificationViews(key);
            addNotificationViews(key, notification);
        }
    } else {
        if (DEBUG)
            Log.d(TAG, "not reusing notification for key: " + key);
        if (DEBUG)
            Log.d(TAG, "contents was " + (contentsUnchanged ? "unchanged" : "changed"));
        if (DEBUG)
            Log.d(TAG, "order was " + (orderUnchanged ? "unchanged" : "changed"));
        if (DEBUG)
            Log.d(TAG, "notification is " + (isTopAnyway ? "top" : "not top"));
        final boolean wasExpanded = (Boolean) XposedHelpers.callMethod(row, "isUserExpanded");
        removeNotificationViews(key);
        // will also replace the heads up
        addNotificationViews(key, notification);
        if (wasExpanded) {
            final Object newEntry = XposedHelpers.callMethod(mNotificationData, "findByKey", key);
            Object nRow = XposedHelpers.getObjectField(newEntry, "row");
            XposedHelpers.callMethod(nRow, "setExpanded", true);
            XposedHelpers.callMethod(nRow, "setUserExpanded", true);
        }
    }
    // Update the veto button accordingly (and as a result, whether this row is
    // swipe-dismissable)
    XposedHelpers.callMethod(self, "updateNotificationVetoButton", row, notification);
    // Is this for you?
    boolean isForCurrentUser = (Boolean) XposedHelpers.callMethod(self, "notificationIsForCurrentUser", notification);
    if (DEBUG)
        Log.d(TAG, "notification is " + (isForCurrentUser ? "" : "not ") + "for you");
    // Restart the ticker if it's still running
    if (updateTicker && isForCurrentUser) {
        XposedHelpers.callMethod(self, "haltTicker");
        XposedHelpers.callMethod(self, "tick", key, notification, false);
    }
    // Recalculate the position of the sliding windows and the titles.
    setAreThereNotifications();
    XposedHelpers.callMethod(self, "updateExpandedViewPos", EXPANDED_LEAVE_ALONE);
    return null;
}
Example 22
Project: test-butler-master  File: PermissionGranter.java View source code
@TargetApi(Build.VERSION_CODES.M)
boolean grantPermission(@NonNull Context context, @NonNull String packageName, @NonNull String permission) {
    try {
        PackageManager packageManager = context.getPackageManager();
        Method method = packageManager.getClass().getMethod("grantRuntimePermission", String.class, String.class, UserHandle.class);
        method.invoke(packageManager, packageName, permission, android.os.Process.myUserHandle());
    } catch (NoSuchMethodException e) {
        Log.e(TAG, "NoSuchMethodException while granting permission", e);
        return false;
    } catch (InvocationTargetException e) {
        Log.e(TAG, "InvocationTargetException while granting permission", e);
        return false;
    } catch (IllegalAccessException e) {
        Log.e(TAG, "IllegalAccessException while granting permission", e);
        return false;
    }
    return true;
}
Example 23
Project: android_packages_apps_Trebuchet-master  File: Launcher.java View source code
// TODO: These method should be a part of LauncherSearchCallback
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
    // Called from search suggestion
    UserHandleCompat user = null;
    if (Utilities.ATLEAST_LOLLIPOP) {
        UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
        if (userHandle != null) {
            user = UserHandleCompat.fromUser(userHandle);
        }
    }
    return createAppDragInfo(appLaunchIntent, user);
}
Example 24
Project: cnAndroidDocs-master  File: WifiStateMachine.java View source code
private void setWifiState(int wifiState) {
    final int previousWifiState = mWifiState.get();
    try {
        if (wifiState == WIFI_STATE_ENABLED) {
            mBatteryStats.noteWifiOn();
        } else if (wifiState == WIFI_STATE_DISABLED) {
            mBatteryStats.noteWifiOff();
        }
    } catch (RemoteException e) {
        loge("Failed to note battery stats in wifi");
    }
    mWifiState.set(wifiState);
    if (DBG)
        log("setWifiState: " + syncGetWifiStateByName());
    final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
    intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
    intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
    mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
Example 25
Project: frameworks_opt-master  File: SMSDispatcher.java View source code
private void checkCallerIsPhoneOrCarrierApp() {
    int uid = Binder.getCallingUid();
    int appId = UserHandle.getAppId(uid);
    if (appId == Process.PHONE_UID || uid == 0) {
        return;
    }
    try {
        PackageManager pm = mContext.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(getCarrierAppPackageName(), 0);
        if (!UserHandle.isSameApp(ai.uid, Binder.getCallingUid())) {
            throw new SecurityException("Caller is not phone or carrier app!");
        }
    } catch (PackageManager.NameNotFoundException re) {
        throw new SecurityException("Caller is not phone or carrier app!");
    }
}
Example 26
Project: Launcher3-master  File: Launcher.java View source code
// TODO: These method should be a part of LauncherSearchCallback
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
    // Called from search suggestion
    UserHandleCompat user = null;
    if (Utilities.ATLEAST_LOLLIPOP) {
        UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
        if (userHandle != null) {
            user = UserHandleCompat.fromUser(userHandle);
        }
    }
    return createAppDragInfo(appLaunchIntent, user);
}
Example 27
Project: platform_packages_providers_mediaprovider-master  File: MtpService.java View source code
/**
     * Manage {@link #mServer}, creating only when running as the current user.
     */
private void manageServiceLocked(StorageVolume primary, String[] subdirs) {
    final boolean isCurrentUser = UserHandle.myUserId() == ActivityManager.getCurrentUser();
    if (mServer == null && isCurrentUser) {
        Log.d(TAG, "starting MTP server in " + (mPtpMode ? "PTP mode" : "MTP mode"));
        mDatabase = new MtpDatabase(this, MediaProvider.EXTERNAL_VOLUME, primary.getPath(), subdirs);
        String deviceSerialNumber = Build.SERIAL;
        if (Build.UNKNOWN.equals(deviceSerialNumber)) {
            deviceSerialNumber = "????????";
        }
        mServer = new MtpServer(mDatabase, mPtpMode, // MTP DeviceInfo: Manufacturer
        Build.MANUFACTURER, // MTP DeviceInfo: Model
        Build.MODEL, // MTP DeviceInfo: Device Version
        "1.0", // MTP DeviceInfo: Serial Number
        deviceSerialNumber);
        mDatabase.setServer(mServer);
        if (!mMtpDisabled) {
            addStorageDevicesLocked();
        }
        mServer.start();
    } else if (mServer != null && !isCurrentUser) {
        Log.d(TAG, "no longer current user; shutting down MTP server");
        // Internally, kernel will close our FD, and server thread will
        // handle cleanup.
        mServer = null;
        mDatabase.setServer(null);
    }
}
Example 28
Project: understand-plugin-framework-master  File: ServiceManager.java View source code
/**
     * 解�Apk文件中的 <service>, 并存储起�
     * 主�是调用PackageParser类的generateServiceInfo方法
     * @param apkFile �件对应的apk文件
     * @throws Exception è§£æž?出错或者å??射调用出错, å?‡ä¼šæŠ›å‡ºå¼‚常
     */
public void preLoadServices(File apkFile) throws Exception {
    Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser");
    Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class);
    Object packageParser = packageParserClass.newInstance();
    // 首先调用parsePackage获�到apk对象对应的Package对象
    Object packageObj = parsePackageMethod.invoke(packageParser, apkFile, PackageManager.GET_SERVICES);
    // 读�Package对象里�的services字段
    // 接下���的就是根�这个List<Service> 获�到Service对应的ServiceInfo
    Field servicesField = packageObj.getClass().getDeclaredField("services");
    List services = (List) servicesField.get(packageObj);
    // 调用generateServiceInfo 方法, 把PackageParser.Service转��ServiceInfo
    Class<?> packageParser$ServiceClass = Class.forName("android.content.pm.PackageParser$Service");
    Class<?> packageUserStateClass = Class.forName("android.content.pm.PackageUserState");
    Class<?> userHandler = Class.forName("android.os.UserHandle");
    Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId");
    int userId = (Integer) getCallingUserIdMethod.invoke(null);
    Object defaultUserState = packageUserStateClass.newInstance();
    // 需�调用 android.content.pm.PackageParser#generateActivityInfo(android.content.pm.ActivityInfo, int, android.content.pm.PackageUserState, int)
    Method generateReceiverInfo = packageParserClass.getDeclaredMethod("generateServiceInfo", packageParser$ServiceClass, int.class, packageUserStateClass, int.class);
    // 解�出intent对应的Service组件
    for (Object service : services) {
        ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser, service, 0, defaultUserState, userId);
        mServiceInfoMap.put(new ComponentName(info.packageName, info.name), info);
    }
}
Example 29
Project: XieDaDeng-master  File: PhoneStatusBar.java View source code
// ================================================================================
// Constructing the view
// ================================================================================
protected PhoneStatusBarView makeStatusBarView() {
    final Context context = mContext;
    Resources res = context.getResources();
    // populates mDisplayMetrics
    updateDisplaySize();
    updateResources();
    mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
    mStatusBarWindow = (StatusBarWindowView) View.inflate(context, R.layout.super_status_bar, null);
    mStatusBarWindow.mService = this;
    mStatusBarWindow.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            checkUserAutohide(v, event);
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (mExpandedVisible) {
                    animateCollapsePanels();
                }
            }
            return mStatusBarWindow.onTouchEvent(event);
        }
    });
    mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
    mStatusBarView.setBar(this);
    PanelHolder holder = (PanelHolder) mStatusBarWindow.findViewById(R.id.panel_holder);
    mStatusBarView.setPanelHolder(holder);
    mNotificationPanel = (NotificationPanelView) mStatusBarWindow.findViewById(R.id.notification_panel);
    mNotificationPanel.setStatusBar(this);
    if (!HIGH_END) {
        mStatusBarWindow.setBackground(null);
        mNotificationPanel.setBackground(new FastColorDrawable(context.getResources().getColor(R.color.notification_panel_solid_background)));
    }
    if (ENABLE_HEADS_UP) {
        mHeadsUpNotificationView = (HeadsUpNotificationView) View.inflate(context, R.layout.heads_up, null);
        mHeadsUpNotificationView.setVisibility(View.GONE);
        mHeadsUpNotificationView.setBar(this);
    }
    if (MULTIUSER_DEBUG) {
        mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(R.id.header_debug_info);
        mNotificationPanelDebugText.setVisibility(View.VISIBLE);
    }
    updateShowSearchHoldoff();
    try {
        boolean showNav = mWindowManagerService.hasNavigationBar();
        if (DEBUG)
            Log.v(TAG, "hasNavigationBar=" + showNav);
        if (showNav) {
            mNavigationBarView = (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
            mNavigationBarView.setDisabledFlags(mDisabled);
            mNavigationBarView.setBar(this);
            mNavigationBarView.setOnVerticalChangedListener(new NavigationBarView.OnVerticalChangedListener() {

                @Override
                public void onVerticalChanged(boolean isVertical) {
                    if (mSearchPanelView != null) {
                        mSearchPanelView.setHorizontal(isVertical);
                    }
                    mNotificationPanel.setQsScrimEnabled(!isVertical);
                }
            });
            mNavigationBarView.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    checkUserAutohide(v, event);
                    return false;
                }
            });
        }
    } catch (RemoteException ex) {
    }
    // figure out which pixel-format to use for the status bar.
    mPixelFormat = PixelFormat.OPAQUE;
    mSystemIconArea = (LinearLayout) mStatusBarView.findViewById(R.id.system_icon_area);
    mSystemIcons = (LinearLayout) mStatusBarView.findViewById(R.id.system_icons);
    mStatusIcons = (LinearLayout) mStatusBarView.findViewById(R.id.statusIcons);
    mNotificationIconArea = mStatusBarView.findViewById(R.id.notification_icon_area_inner);
    mNotificationIcons = (IconMerger) mStatusBarView.findViewById(R.id.notificationIcons);
    mMoreIcon = mStatusBarView.findViewById(R.id.moreIcon);
    mNotificationIcons.setOverflowIndicator(mMoreIcon);
    mStatusBarContents = (LinearLayout) mStatusBarView.findViewById(R.id.status_bar_contents);
    mStackScroller = (NotificationStackScrollLayout) mStatusBarWindow.findViewById(R.id.notification_stack_scroller);
    mStackScroller.setLongPressListener(getNotificationLongClicker());
    mStackScroller.setPhoneStatusBar(this);
    mKeyguardIconOverflowContainer = (NotificationOverflowContainer) LayoutInflater.from(mContext).inflate(R.layout.status_bar_notification_keyguard_overflow, mStackScroller, false);
    mKeyguardIconOverflowContainer.setOnActivatedListener(this);
    mKeyguardIconOverflowContainer.setOnClickListener(mOverflowClickListener);
    mStackScroller.addView(mKeyguardIconOverflowContainer);
    SpeedBumpView speedBump = (SpeedBumpView) LayoutInflater.from(mContext).inflate(R.layout.status_bar_notification_speed_bump, mStackScroller, false);
    mStackScroller.setSpeedBumpView(speedBump);
    mEmptyShadeView = (EmptyShadeView) LayoutInflater.from(mContext).inflate(R.layout.status_bar_no_notifications, mStackScroller, false);
    mStackScroller.setEmptyShadeView(mEmptyShadeView);
    mDismissView = (DismissView) LayoutInflater.from(mContext).inflate(R.layout.status_bar_notification_dismiss_all, mStackScroller, false);
    mDismissView.setOnButtonClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            clearAllNotifications();
        }
    });
    mStackScroller.setDismissView(mDismissView);
    mExpandedContents = mStackScroller;
    mBackdrop = (BackDropView) mStatusBarWindow.findViewById(R.id.backdrop);
    mBackdropFront = (ImageView) mBackdrop.findViewById(R.id.backdrop_front);
    mBackdropBack = (ImageView) mBackdrop.findViewById(R.id.backdrop_back);
    ScrimView scrimBehind = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_behind);
    ScrimView scrimInFront = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_in_front);
    mScrimController = new ScrimController(scrimBehind, scrimInFront, mScrimSrcModeEnabled);
    mScrimController.setBackDropView(mBackdrop);
    mStatusBarView.setScrimController(mScrimController);
    mDozeScrimController = new DozeScrimController(mScrimController, context);
    mHeader = (StatusBarHeaderView) mStatusBarWindow.findViewById(R.id.header);
    mHeader.setActivityStarter(this);
    mKeyguardStatusBar = (KeyguardStatusBarView) mStatusBarWindow.findViewById(R.id.keyguard_header);
    mStatusIconsKeyguard = (LinearLayout) mKeyguardStatusBar.findViewById(R.id.statusIcons);
    mKeyguardStatusView = mStatusBarWindow.findViewById(R.id.keyguard_status_view);
    mKeyguardBottomArea = (KeyguardBottomAreaView) mStatusBarWindow.findViewById(R.id.keyguard_bottom_area);
    mKeyguardBottomArea.setActivityStarter(this);
    mKeyguardIndicationController = new KeyguardIndicationController(mContext, (KeyguardIndicationTextView) mStatusBarWindow.findViewById(R.id.keyguard_indication_text));
    mKeyguardBottomArea.setKeyguardIndicationController(mKeyguardIndicationController);
    mTickerEnabled = res.getBoolean(R.bool.enable_ticker);
    if (mTickerEnabled) {
        final ViewStub tickerStub = (ViewStub) mStatusBarView.findViewById(R.id.ticker_stub);
        if (tickerStub != null) {
            mTickerView = tickerStub.inflate();
            mTicker = new MyTicker(context, mStatusBarView);
            TickerView tickerView = (TickerView) mStatusBarView.findViewById(R.id.tickerText);
            tickerView.mTicker = mTicker;
        }
    }
    mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
    // set the inital view visibility
    setAreThereNotifications();
    // Background thread for any controllers that need it.
    mHandlerThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();
    // Other icons
    // will post a notification
    mLocationController = new LocationControllerImpl(mContext);
    mBatteryController = new BatteryController(mContext);
    mBatteryController.addStateChangedCallback(new BatteryStateChangeCallback() {

        @Override
        public void onPowerSaveChanged() {
            mHandler.post(mCheckBarModes);
            if (mDozeServiceHost != null) {
                mDozeServiceHost.firePowerSaveChanged(mBatteryController.isPowerSave());
            }
        }

        @Override
        public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
        // noop
        }
    });
    mNetworkController = new NetworkControllerImpl(mContext);
    mHotspotController = new HotspotControllerImpl(mContext);
    //SPRD:fixbug434711 make the statusbar close when click hotspot
    mHotspotController.setbar(this);
    mBluetoothController = new BluetoothControllerImpl(mContext, mHandlerThread.getLooper());
    mSecurityController = new SecurityControllerImpl(mContext);
    if (mContext.getResources().getBoolean(R.bool.config_showRotationLock)) {
        mRotationLockController = new RotationLockControllerImpl(mContext);
    }
    mUserInfoController = new UserInfoController(mContext);
    mVolumeComponent = getComponent(VolumeComponent.class);
    if (mVolumeComponent != null) {
        mZenModeController = mVolumeComponent.getZenController();
    }
    mCastController = new CastControllerImpl(mContext);
    final SignalClusterView signalCluster = (SignalClusterView) mStatusBarView.findViewById(R.id.signal_cluster);
    final SignalClusterView signalClusterKeyguard = (SignalClusterView) mKeyguardStatusBar.findViewById(R.id.signal_cluster);
    final SignalClusterView signalClusterQs = (SignalClusterView) mHeader.findViewById(R.id.signal_cluster);
    mNetworkController.addSignalCluster(signalCluster);
    mNetworkController.addSignalCluster(signalClusterKeyguard);
    mNetworkController.addSignalCluster(signalClusterQs);
    signalCluster.setSecurityController(mSecurityController);
    signalCluster.setNetworkController(mNetworkController);
    signalClusterKeyguard.setSecurityController(mSecurityController);
    signalClusterKeyguard.setNetworkController(mNetworkController);
    signalClusterQs.setSecurityController(mSecurityController);
    signalClusterQs.setNetworkController(mNetworkController);
    final boolean isAPhone = mNetworkController.hasVoiceCallingFeature();
    if (isAPhone) {
        mNetworkController.addEmergencyListener(new NetworkControllerImpl.EmergencyListener() {

            @Override
            public void setEmergencyCallsOnly(boolean emergencyOnly) {
                mHeader.setShowEmergencyCallsOnly(emergencyOnly);
            }
        });
    }
    /* SPRD: bug419269 modify for network name display @{ */
    mCarrierLabel = (LinearLayout) mStatusBarWindow.findViewById(R.id.carrier_label_group);
    LayoutInflater inflater = LayoutInflater.from(mContext);
    mShowCarrierInPanel = (mCarrierLabel != null);
    if (DEBUG)
        Log.v(TAG, "carrierlabel=" + mCarrierLabel + " show=" + mShowCarrierInPanel);
    if (mShowCarrierInPanel) {
        mCarrierLabel.setVisibility(mCarrierLabelVisible ? View.VISIBLE : View.INVISIBLE);
        final int phoneCount = TelephonyManager.from(mContext).getPhoneCount();
        mCarrierLabelItems = new TextView[phoneCount];
        //for (int i = phoneCount - 1; i >= 0; i--) {
        for (int i = 0; i < phoneCount; i++) {
            mCarrierLabelItems[i] = (TextView) inflater.inflate(R.layout.carrier_label, null);
            mCarrierLabel.addView(mCarrierLabelItems[i]);
        }
        mNetworkController.addCarrierLabel(new NetworkControllerImpl.CarrierLabelListener() {

            @Override
            public void setCarrierLabel(SpannableStringBuilder label) {
                Log.d(TAG, "label = " + label);
                ForegroundColorSpan[] spans = label.getSpans(0, label.length(), ForegroundColorSpan.class);
                for (int i = 0; i < phoneCount; i++) {
                    CharSequence carrierLabel = "";
                    if (i < spans.length) {
                        int startIndex = label.getSpanStart(spans[i]);
                        int endIndex = label.getSpanEnd(spans[i]);
                        carrierLabel = label.subSequence(startIndex, endIndex);
                    }
                    mCarrierLabelItems[i].setText(carrierLabel);
                    if (TextUtils.isEmpty(carrierLabel)) {
                        mCarrierLabelItems[i].setVisibility(View.GONE);
                    } else {
                        mCarrierLabelItems[i].setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }
    /* @} */
    mFlashlightController = new FlashlightController(mContext);
    mKeyguardBottomArea.setFlashlightController(mFlashlightController);
    mKeyguardBottomArea.setPhoneStatusBar(this);
    mAccessibilityController = new AccessibilityController(mContext);
    mKeyguardBottomArea.setAccessibilityController(mAccessibilityController);
    mNextAlarmController = new NextAlarmController(mContext);
    mKeyguardMonitor = new KeyguardMonitor();
    if (UserSwitcherController.isUserSwitcherAvailable(UserManager.get(mContext))) {
        mUserSwitcherController = new UserSwitcherController(mContext, mKeyguardMonitor);
    }
    mKeyguardUserSwitcher = new KeyguardUserSwitcher(mContext, (ViewStub) mStatusBarWindow.findViewById(R.id.keyguard_user_switcher), mKeyguardStatusBar, mNotificationPanel, mUserSwitcherController);
    // Set up the quick settings tile panel
    mQSPanel = (QSPanel) mStatusBarWindow.findViewById(R.id.quick_settings_panel);
    if (mQSPanel != null) {
        final QSTileHost qsh = new QSTileHost(mContext, this, mBluetoothController, mLocationController, mRotationLockController, mNetworkController, mZenModeController, mHotspotController, mCastController, mFlashlightController, mUserSwitcherController, mKeyguardMonitor, mSecurityController);
        mQSPanel.setHost(qsh);
        mQSPanel.setTiles(qsh.getTiles());
        mBrightnessMirrorController = new BrightnessMirrorController(mStatusBarWindow);
        mQSPanel.setBrightnessMirror(mBrightnessMirrorController);
        mHeader.setQSPanel(mQSPanel);
        qsh.setCallback(new QSTileHost.Callback() {

            @Override
            public void onTilesChanged() {
                mQSPanel.setTiles(qsh.getTiles());
            }
        });
    }
    // User info. Trigger first load.
    mHeader.setUserInfoController(mUserInfoController);
    mKeyguardStatusBar.setUserInfoController(mUserInfoController);
    mUserInfoController.reloadUserInfo();
    mHeader.setBatteryController(mBatteryController);
    ((BatteryMeterView) mStatusBarView.findViewById(R.id.battery)).setBatteryController(mBatteryController);
    mKeyguardStatusBar.setBatteryController(mBatteryController);
    mHeader.setNextAlarmController(mNextAlarmController);
    PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    mBroadcastReceiver.onReceive(mContext, new Intent(pm.isScreenOn() ? Intent.ACTION_SCREEN_ON : Intent.ACTION_SCREEN_OFF));
    // receive broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    if (DEBUG_MEDIA_FAKE_ARTWORK) {
        filter.addAction("fake_artwork");
    }
    filter.addAction(ACTION_DEMO);
    context.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
    // listen for USER_SETUP_COMPLETE setting (per-user)
    resetUserSetupObserver();
    startGlyphRasterizeHack();
    return mStatusBarView;
}
Example 30
Project: TwsPluginFramework-master  File: RemoteViewsAdapter.java View source code
public synchronized void bind(Context context, int appWidgetId, Intent intent) {
    if (!mIsConnecting) {
        try {
            RemoteViewsAdapter adapter;
            final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
            if ((adapter = mAdapter.get()) != null) {
                checkInteractAcrossUsersPermission(context, adapter.mUserId);
                mgr.bindRemoteViewsService(appWidgetId, intent, asBinder(), new UserHandle(adapter.mUserId));
            } else {
                Slog.w(TAG, "bind: adapter was null");
            }
            mIsConnecting = true;
        } catch (Exception e) {
            Log.e("RemoteViewsAdapterServiceConnection", "bind(): " + e.getMessage());
            mIsConnecting = false;
            mIsConnected = false;
        }
    }
}
Example 31
Project: Amigo-master  File: AmigoInstrumentation.java View source code
@Override
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options, UserHandle user) {
    try {
        intent = wrapIntent(who, intent);
        if (methodExecStart5 == null)
            methodExecStart5 = oldInstrumentation.getClass().getDeclaredMethod("execStartActivity", Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class, int.class, Bundle.class, UserHandle.class);
        return (ActivityResult) methodExecStart5.invoke(oldInstrumentation, who, contextThread, token, target, intent, requestCode, options, user);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return null;
}
Example 32
Project: Android-Plugin-Framework-master  File: FakeUtil.java View source code
@Override
public PackageManager getPackageManager() {
    final PackageManager pm = super.getPackageManager();
    return new PackageManager() {

        @Override
        public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
            if ((flags & PackageManager.GET_SIGNATURES) != 0) {
                //返回宿主签å??
                packageInfo.signatures = pm.getPackageInfo(getPackageName(), flags).signatures;
            }
            return packageInfo;
        }

        @Override
        public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException {
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, flags);
            if ((flags & PackageManager.GET_META_DATA) != 0) {
                Context context = getBaseContext();
                while (context instanceof ContextWrapper) {
                    context = ((ContextWrapper) context).getBaseContext();
                }
                //返回宿主meta
                applicationInfo.metaData = context.getApplicationInfo().metaData;
            }
            return applicationInfo;
        }

        @Override
        public ActivityInfo getActivityInfo(ComponentName component, int flags) throws NameNotFoundException {
            return pm.getActivityInfo(component, flags);
        }

        @Override
        public ActivityInfo getReceiverInfo(ComponentName component, int flags) throws NameNotFoundException {
            return pm.getReceiverInfo(component, flags);
        }

        @Override
        public ServiceInfo getServiceInfo(ComponentName component, int flags) throws NameNotFoundException {
            return pm.getServiceInfo(component, flags);
        }

        @Override
        public ProviderInfo getProviderInfo(ComponentName component, int flags) throws NameNotFoundException {
            return pm.getProviderInfo(component, flags);
        }

        @Override
        public List<PackageInfo> getInstalledPackages(int flags) {
            return pm.getInstalledPackages(flags);
        }

        @Override
        public int checkSignatures(String pkg1, String pkg2) {
            return pm.checkSignatures(pkg1, pkg2);
        }

        @Override
        public int checkSignatures(int uid1, int uid2) {
            return pm.checkSignatures(uid1, uid2);
        }

        @Override
        public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
            return pm.queryBroadcastReceivers(intent, flags);
        }

        //methods belows is not need, remain empty impl
        @Override
        public String[] currentToCanonicalPackageNames(String[] names) {
            return new String[0];
        }

        @Override
        public String[] canonicalToCurrentPackageNames(String[] names) {
            return new String[0];
        }

        @Override
        public Intent getLaunchIntentForPackage(String packageName) {
            return null;
        }

        @Override
        public Intent getLeanbackLaunchIntentForPackage(String packageName) {
            return null;
        }

        @Override
        public int[] getPackageGids(String packageName) throws NameNotFoundException {
            return new int[0];
        }

        //@Override //android-N
        public int[] getPackageGids(String packageName, int flags) throws NameNotFoundException {
            return new int[0];
        }

        @Override
        public PermissionInfo getPermissionInfo(String name, int flags) throws NameNotFoundException {
            return null;
        }

        @Override
        public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) throws NameNotFoundException {
            return null;
        }

        @Override
        public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) throws NameNotFoundException {
            return null;
        }

        @Override
        public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
            return null;
        }

        @Override
        public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions, int flags) {
            return null;
        }

        @Override
        public int checkPermission(String permName, String pkgName) {
            return 0;
        }

        @Override
        public boolean isPermissionRevokedByPolicy(String permName, String pkgName) {
            return false;
        }

        @Override
        public boolean addPermission(PermissionInfo info) {
            return false;
        }

        @Override
        public boolean addPermissionAsync(PermissionInfo info) {
            return false;
        }

        @Override
        public void removePermission(String name) {
        }

        @Nullable
        @Override
        public String[] getPackagesForUid(int uid) {
            return new String[0];
        }

        @Nullable
        @Override
        public String getNameForUid(int uid) {
            return null;
        }

        @Override
        public List<ApplicationInfo> getInstalledApplications(int flags) {
            return null;
        }

        @Override
        public String[] getSystemSharedLibraryNames() {
            return new String[0];
        }

        @Override
        public FeatureInfo[] getSystemAvailableFeatures() {
            return new FeatureInfo[0];
        }

        @Override
        public boolean hasSystemFeature(String name) {
            return false;
        }

        @Override
        public ResolveInfo resolveActivity(Intent intent, int flags) {
            return null;
        }

        @Override
        public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
            return null;
        }

        @Override
        public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics, Intent intent, int flags) {
            return null;
        }

        @Override
        public ResolveInfo resolveService(Intent intent, int flags) {
            return null;
        }

        @Override
        public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
            return null;
        }

        @Override
        public List<ResolveInfo> queryIntentContentProviders(Intent intent, int flags) {
            return null;
        }

        @Override
        public ProviderInfo resolveContentProvider(String name, int flags) {
            return null;
        }

        @Override
        public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) {
            return null;
        }

        @Override
        public InstrumentationInfo getInstrumentationInfo(ComponentName className, int flags) throws NameNotFoundException {
            return null;
        }

        @Override
        public List<InstrumentationInfo> queryInstrumentation(String targetPackage, int flags) {
            return null;
        }

        @Override
        public Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo) {
            return null;
        }

        @Override
        public Drawable getActivityIcon(ComponentName activityName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getActivityIcon(Intent intent) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getActivityBanner(ComponentName activityName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getActivityBanner(Intent intent) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getDefaultActivityIcon() {
            return null;
        }

        @Override
        public Drawable getApplicationIcon(ApplicationInfo info) {
            return null;
        }

        @Override
        public Drawable getApplicationIcon(String packageName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getApplicationBanner(ApplicationInfo info) {
            return null;
        }

        @Override
        public Drawable getApplicationBanner(String packageName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getActivityLogo(ComponentName activityName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getActivityLogo(Intent intent) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getApplicationLogo(ApplicationInfo info) {
            return null;
        }

        @Override
        public Drawable getApplicationLogo(String packageName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) {
            return null;
        }

        @Override
        public Drawable getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user, Rect badgeLocation, int badgeDensity) {
            return null;
        }

        @Override
        public CharSequence getUserBadgedLabel(CharSequence label, UserHandle user) {
            return null;
        }

        @Override
        public CharSequence getText(String packageName, int resid, ApplicationInfo appInfo) {
            return null;
        }

        @Override
        public XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo) {
            return null;
        }

        @Override
        public CharSequence getApplicationLabel(ApplicationInfo info) {
            return null;
        }

        @Override
        public Resources getResourcesForActivity(ComponentName activityName) throws NameNotFoundException {
            return null;
        }

        @Override
        public Resources getResourcesForApplication(ApplicationInfo app) throws NameNotFoundException {
            return null;
        }

        @Override
        public Resources getResourcesForApplication(String appPackageName) throws NameNotFoundException {
            return null;
        }

        @Override
        public void verifyPendingInstall(int id, int verificationCode) {
        }

        @Override
        public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, long millisecondsToDelay) {
        }

        @Override
        public void setInstallerPackageName(String targetPackage, String installerPackageName) {
        }

        @Override
        public String getInstallerPackageName(String packageName) {
            return null;
        }

        @Override
        public void addPackageToPreferred(String packageName) {
        }

        @Override
        public void removePackageFromPreferred(String packageName) {
        }

        @Override
        public List<PackageInfo> getPreferredPackages(int flags) {
            return null;
        }

        @Override
        public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) {
        }

        @Override
        public void clearPackagePreferredActivities(String packageName) {
        }

        @Override
        public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) {
            return 0;
        }

        @Override
        public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) {
        }

        @Override
        public int getComponentEnabledSetting(ComponentName componentName) {
            return 0;
        }

        @Override
        public void setApplicationEnabledSetting(String packageName, int newState, int flags) {
        }

        @Override
        public int getApplicationEnabledSetting(String packageName) {
            return 0;
        }

        @Override
        public boolean isSafeMode() {
            return false;
        }

        @NonNull
        @Override
        public PackageInstaller getPackageInstaller() {
            return null;
        }

        //@Override //android-N
        public boolean hasSystemFeature(String name, int flag) {
            return false;
        }

        //@Override //android-N
        public int getPackageUid(String name, int flag) {
            return 0;
        }
    };
}
Example 33
Project: android_packages_providers_MediaProvider-master  File: MtpService.java View source code
/**
     * Manage {@link #mServer}, creating only when running as the current user.
     */
private void manageServiceLocked(StorageVolume primary, String[] subdirs) {
    final boolean isCurrentUser = UserHandle.myUserId() == ActivityManager.getCurrentUser();
    if (mServer == null && isCurrentUser) {
        Log.d(TAG, "starting MTP server in " + (mPtpMode ? "PTP mode" : "MTP mode"));
        mDatabase = new MtpDatabase(this, MediaProvider.EXTERNAL_VOLUME, primary.getPath(), subdirs);
        mServer = new MtpServer(mDatabase, mPtpMode);
        mDatabase.setServer(mServer);
        if (!mMtpDisabled) {
            addStorageDevicesLocked();
        }
        mServer.start();
    } else if (mServer != null && !isCurrentUser) {
        Log.d(TAG, "no longer current user; shutting down MTP server");
        // Internally, kernel will close our FD, and server thread will
        // handle cleanup.
        mServer = null;
        mDatabase.setServer(null);
    }
}
Example 34
Project: ApkLauncher-master  File: TargetInstrumentation.java View source code
public static int myUseId() {
    int userId = -1;
    try {
        Method myUserIdM = Class.forName("android.os.UserHandle").getDeclaredMethod("myUseId", (Class[]) null);
        myUserIdM.setAccessible(true);
        userId = ((Integer) myUserIdM.invoke(null, (Object[]) null));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return userId;
}
Example 35
Project: platform_packages_providers_contactsprovider-master  File: CallLogProvider.java View source code
/**
     * Sync all calllog entries that were inserted
     */
private void syncEntries() {
    if (isShadow()) {
        // It's the shadow provider itself.  No copying.
        return;
    }
    final UserManager userManager = UserUtils.getUserManager(getContext());
    // TODO: http://b/24944959
    if (!Calls.shouldHaveSharedCallLogEntries(getContext(), userManager, userManager.getUserHandle())) {
        return;
    }
    final int myUserId = userManager.getUserHandle();
    if (userManager.isSystemUser()) {
        // If it's the system user, just copy from shadow.
        syncEntriesFrom(UserHandle.USER_SYSTEM, /* sourceIsShadow = */
        true, /* forAllUsersOnly =*/
        false);
    } else {
        // Otherwise, copy from system's real provider, as well as self's shadow.
        syncEntriesFrom(UserHandle.USER_SYSTEM, /* sourceIsShadow = */
        false, /* forAllUsersOnly =*/
        true);
        syncEntriesFrom(myUserId, /* sourceIsShadow = */
        true, /* forAllUsersOnly =*/
        false);
    }
}
Example 36
Project: XUtilities-master  File: ModBrightness.java View source code
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
    if (SystemClock.elapsedRealtime() < 60 * 1000) {
        // 起動一分以内�何も���
        return;
    }
    Context mContext = (Context) XposedHelpers.getAdditionalInstanceField(param.thisObject, "mContext");
    Object mScreenAutoBrightness = XposedHelpers.getObjectField(param.thisObject, "mScreenAutoBrightness");
    Object mAmbientLux = XposedHelpers.getObjectField(param.thisObject, "mAmbientLux");
    Intent intent = new Intent(AutoBrightnessController.ACTION_AUTO_BRIGHTNESS_CHANGED);
    intent.putExtra(AutoBrightnessController.EXTRA_BRIGHTNESS, (Integer) mScreenAutoBrightness);
    intent.putExtra(AutoBrightnessController.EXTRA_LUX, (Float) mAmbientLux);
    // センサー値��度をブロードキャスト��信
    UserHandle user = (UserHandle) XposedHelpers.getStaticObjectField(UserHandle.class, "ALL");
    mContext.sendBroadcastAsUser(intent, user);
}
Example 37
Project: android_device_asus_me301t-master  File: DeviceBroadcastReceiver.java View source code
private void displayKeyPadNotification(Context ctx, String title, int icon) {
    // Cancel any running notification callback
    synchronized (mLock) {
        mHandler.removeCallbacks(mCancelKpNotifications);
    }
    Notification notification = new Notification.Builder(ctx).setContentTitle(title).setTicker(title).setSmallIcon(icon).setDefaults(// be quiet
    0).setSound(null).setVibrate(null).setOngoing(true).setWhen(0).setPriority(Notification.PRIORITY_LOW).build();
    mNotificationManager.notifyAsUser(null, NOTIFICATION_ID, notification, UserHandle.ALL);
    // Post a delayed cancellation of the notification
    mHandler.postDelayed(mCancelKpNotifications, mNotificationTimeout);
}
Example 38
Project: packages_apps_ROMControl-master  File: ButtonSettingsFragment.java View source code
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    ContentResolver mResolver = getActivity().getContentResolver();
    if (preference == mEnableHwKeys) {
        boolean hWkeysValue = (Boolean) newValue;
        Settings.Secure.putInt(mResolver, Settings.Secure.ENABLE_HW_KEYS, hWkeysValue ? 1 : 0);
        writeDisableHwKeysOption(getActivity(), hWkeysValue);
        updateDisableHwKeysOption();
        return true;
    } else if (preference == mHomeLongPressAction) {
        handleActionListChange(mHomeLongPressAction, newValue, CMSettings.System.KEY_HOME_LONG_PRESS_ACTION);
        return true;
    } else if (preference == mHomeDoubleTapAction) {
        handleActionListChange(mHomeDoubleTapAction, newValue, CMSettings.System.KEY_HOME_DOUBLE_TAP_ACTION);
        return true;
    } else if (preference == mMenuPressAction) {
        handleActionListChange(mMenuPressAction, newValue, CMSettings.System.KEY_MENU_ACTION);
        return true;
    } else if (preference == mMenuLongPressAction) {
        handleActionListChange(mMenuLongPressAction, newValue, CMSettings.System.KEY_MENU_LONG_PRESS_ACTION);
        return true;
    } else if (preference == mAssistPressAction) {
        handleActionListChange(mAssistPressAction, newValue, CMSettings.System.KEY_ASSIST_ACTION);
        return true;
    } else if (preference == mAssistLongPressAction) {
        handleActionListChange(mAssistLongPressAction, newValue, CMSettings.System.KEY_ASSIST_LONG_PRESS_ACTION);
        return true;
    } else if (preference == mAppSwitchPressAction) {
        handleActionListChange(mAppSwitchPressAction, newValue, CMSettings.System.KEY_APP_SWITCH_ACTION);
        return true;
    } else if (preference == mAppSwitchLongPressAction) {
        handleActionListChange(mAppSwitchLongPressAction, newValue, CMSettings.System.KEY_APP_SWITCH_LONG_PRESS_ACTION);
        return true;
    } else if (preference == mVolumeKeyCursorControl) {
        handleSystemActionListChange(mVolumeKeyCursorControl, newValue, Settings.System.VOLUME_KEY_CURSOR_CONTROL);
        return true;
    } else if (preference == mCameraDoubleTapPowerGesture) {
        boolean value = (Boolean) newValue;
        Settings.Secure.putInt(mResolver, Settings.Secure.CAMERA_DOUBLE_TAP_POWER_GESTURE_DISABLED, value ? 0 : 1);
    } else if (preference == mDisableFullscreenKeyboard) {
        Settings.System.putInt(mResolver, Settings.System.DISABLE_FULLSCREEN_KEYBOARD, (Boolean) newValue ? 1 : 0);
        return true;
    } else if (preference == mKeyboardRotationToggle) {
        boolean isAutoRotate = (Settings.System.getIntForUser(mResolver, Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) == 1);
        if (isAutoRotate && (Boolean) newValue) {
            showDialogInner(DLG_KEYBOARD_ROTATION);
        }
        Settings.System.putInt(mResolver, Settings.System.KEYBOARD_ROTATION_TIMEOUT, (Boolean) newValue ? KEYBOARD_ROTATION_TIMEOUT_DEFAULT : 0);
        updateRotationTimeout(KEYBOARD_ROTATION_TIMEOUT_DEFAULT);
        return true;
    } else if (preference == mShowEnterKey) {
        Settings.System.putInt(mResolver, Settings.System.FORMAL_TEXT_INPUT, (Boolean) newValue ? 1 : 0);
        return true;
    } else if (preference == mKeyboardRotationTimeout) {
        int timeout = Integer.parseInt((String) newValue);
        Settings.System.putInt(mResolver, Settings.System.KEYBOARD_ROTATION_TIMEOUT, timeout);
        updateRotationTimeout(timeout);
        return true;
    } else if (preference == mKillAppLongPressBack) {
        boolean value = (Boolean) newValue;
        Settings.Secure.putInt(mResolver, Settings.Secure.KILL_APP_LONGPRESS_BACK, value ? 1 : 0);
        return true;
    } else if (preference == mKillAppLongpressTimeout) {
        int killconf = (Integer) newValue;
        Settings.Secure.putInt(mResolver, Settings.Secure.KILL_APP_LONGPRESS_TIMEOUT, killconf);
        return true;
    } else if (preference == mDt2lCameraVibrateConfig) {
        int dt2lcameravib = (Integer) newValue;
        Settings.System.putInt(mResolver, Settings.System.DT2L_CAMERA_VIBRATE_CONFIG, dt2lcameravib * 10);
        return true;
    }
    return false;
}
Example 39
Project: platform_packages_apps_packageinstaller-master  File: AppPermissionGroup.java View source code
public static AppPermissionGroup create(Context context, PackageInfo packageInfo, PackageItemInfo groupInfo, List<PermissionInfo> permissionInfos, UserHandle userHandle) {
    AppPermissionGroup group = new AppPermissionGroup(context, packageInfo, groupInfo.name, groupInfo.packageName, groupInfo.loadLabel(context.getPackageManager()), loadGroupDescription(context, groupInfo), groupInfo.packageName, groupInfo.icon, userHandle);
    if (groupInfo instanceof PermissionInfo) {
        permissionInfos = new ArrayList<>();
        permissionInfos.add((PermissionInfo) groupInfo);
    }
    if (permissionInfos == null || permissionInfos.isEmpty()) {
        return null;
    }
    final int permissionCount = packageInfo.requestedPermissions.length;
    for (int i = 0; i < permissionCount; i++) {
        String requestedPermission = packageInfo.requestedPermissions[i];
        PermissionInfo requestedPermissionInfo = null;
        for (PermissionInfo permissionInfo : permissionInfos) {
            if (requestedPermission.equals(permissionInfo.name)) {
                requestedPermissionInfo = permissionInfo;
                break;
            }
        }
        if (requestedPermissionInfo == null) {
            continue;
        }
        // Collect only runtime permissions.
        if (requestedPermissionInfo.protectionLevel != PermissionInfo.PROTECTION_DANGEROUS) {
            continue;
        }
        // Don't allow toggling non-platform permission groups for legacy apps via app ops.
        if (packageInfo.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1 && !PLATFORM_PACKAGE_NAME.equals(groupInfo.packageName)) {
            continue;
        }
        final boolean granted = (packageInfo.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0;
        final String appOp = PLATFORM_PACKAGE_NAME.equals(requestedPermissionInfo.packageName) ? AppOpsManager.permissionToOp(requestedPermissionInfo.name) : null;
        final boolean appOpAllowed = appOp != null && context.getSystemService(AppOpsManager.class).checkOpNoThrow(appOp, packageInfo.applicationInfo.uid, packageInfo.packageName) == AppOpsManager.MODE_ALLOWED;
        final int flags = context.getPackageManager().getPermissionFlags(requestedPermission, packageInfo.packageName, userHandle);
        Permission permission = new Permission(requestedPermission, granted, appOp, appOpAllowed, flags);
        group.addPermission(permission);
    }
    return group;
}
Example 40
Project: Pure-File-Manager-master  File: MediaHelper.java View source code
@SuppressLint("NewApi")
static int myUserId() {
    try {
        final Method myUserIdMethod = android.os.UserHandle.class.getMethod("myUserId");
        myUserIdMethod.setAccessible(true);
        return (Integer) myUserIdMethod.invoke(null);
    } catch (NoSuchMethodExceptionIllegalAccessException | InvocationTargetException |  e) {
        e.printStackTrace();
    }
    return 0;
}
Example 41
Project: ApkLauncher_legacy-master  File: InstrumentationWrapper.java View source code
private int myUseId() {
    int userId = -1;
    try {
        Method myUserIdM = Class.forName("android.os.UserHandle").getDeclaredMethod("myUseId", (Class[]) null);
        myUserIdM.setAccessible(true);
        userId = ((Integer) myUserIdM.invoke(null, (Object[]) null));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return userId;
}
Example 42
Project: babel-master  File: BabelService.java View source code
private void clearGoogleVoiceNotifications() {
    try {
        if (cancelAllNotifications == null) {
            // run this to get the internal service to populate
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.cancelAll();
            Field f = NotificationManager.class.getDeclaredField("sService");
            f.setAccessible(true);
            internalNotificationService = f.get(null);
            cancelAllNotifications = internalNotificationService.getClass().getDeclaredMethod("cancelAllNotifications", String.class, int.class);
            userId = (Integer) UserHandle.class.getDeclaredMethod("myUserId").invoke(null);
        }
        if (cancelAllNotifications != null)
            cancelAllNotifications.invoke(internalNotificationService, Helper.GOOGLE_VOICE_PACKAGE, userId);
    } catch (Exception e) {
        Log.d(LOGTAG, "Error clearing GoogleVoice notifications", e);
    }
}
Example 43
Project: condom-master  File: CondomContext.java View source code
@RequiresApi(JELLY_BEAN_MR1)
@Override
public void sendOrderedBroadcastAsUser(final Intent intent, final UserHandle user, final String receiverPermission, final BroadcastReceiver resultReceiver, final Handler scheduler, final int initialCode, final String initialData, final Bundle initialExtras) {
    mCondom.proceedBroadcast(intent, new CondomCore.WrappedProcedure() {

        @Override
        public void run() {
            CondomContext.super.sendOrderedBroadcastAsUser(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
        }
    });
}
Example 44
Project: SMouse-and-Faketooth-master  File: PowerManagerService.java View source code
public void systemReady(TwilightService twilight, DreamManagerService dreamManager) {
    synchronized (mLock) {
        mSystemReady = true;
        mDreamManager = dreamManager;
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
        mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
        mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
        SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
        // The notifier runs on the system server's main looper so as not to interfere
        // with the animations and other critical functions of the power manager.
        mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats, mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"), mScreenOnBlocker, mPolicy);
        // The display power controller runs on the power manager service's
        // own handler thread to ensure timely operation.
        mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(), mContext, mNotifier, mLightsService, twilight, sensorManager, mDisplayManagerService, mDisplaySuspendBlocker, mDisplayBlanker, mDisplayPowerControllerCallbacks, mHandler);
        mWirelessChargerDetector = new WirelessChargerDetector(sensorManager, createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"), mHandler);
        mSettingsObserver = new SettingsObserver(mHandler);
        mAttentionLight = mLightsService.getLight(LightsService.LIGHT_ID_ATTENTION);
        // Register for broadcasts from other components of the system.
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
        mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DREAMING_STARTED);
        filter.addAction(Intent.ACTION_DREAMING_STOPPED);
        mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_USER_SWITCHED);
        mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DOCK_EVENT);
        mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
        // Register for settings changes.
        final ContentResolver resolver = mContext.getContentResolver();
        resolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.SCREENSAVER_ENABLED), false, mSettingsObserver, UserHandle.USER_ALL);
        resolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), false, mSettingsObserver, UserHandle.USER_ALL);
        resolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK), false, mSettingsObserver, UserHandle.USER_ALL);
        resolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_OFF_TIMEOUT), false, mSettingsObserver, UserHandle.USER_ALL);
        resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.STAY_ON_WHILE_PLUGGED_IN), false, mSettingsObserver, UserHandle.USER_ALL);
        resolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), false, mSettingsObserver, UserHandle.USER_ALL);
        resolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE), false, mSettingsObserver, UserHandle.USER_ALL);
        // Go.
        readConfigurationLocked();
        updateSettingsLocked();
        mDirty |= DIRTY_BATTERY_STATE;
        updatePowerStateLocked();
    }
}
Example 45
Project: attentive-ui-master  File: Monkey.java View source code
/**
     * Using the restrictions provided (categories & packages), generate a list
     * of activities that we can actually switch to.
     *
     * @return Returns true if it could successfully build a list of target
     *         activities
     */
private boolean getMainApps() {
    try {
        final int N = mMainCategories.size();
        for (int i = 0; i < N; i++) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            String category = mMainCategories.get(i);
            if (category.length() > 0) {
                intent.addCategory(category);
            }
            List<ResolveInfo> mainApps = mPm.queryIntentActivities(intent, null, 0, UserHandle.myUserId());
            if (mainApps == null || mainApps.size() == 0) {
                System.err.println("// Warning: no activities found for category " + category);
                continue;
            }
            if (mVerbose >= 2) {
                // very verbose
                System.out.println("// Selecting main activities from category " + category);
            }
            final int NA = mainApps.size();
            for (int a = 0; a < NA; a++) {
                ResolveInfo r = mainApps.get(a);
                String packageName = r.activityInfo.applicationInfo.packageName;
                if (checkEnteringPackage(packageName)) {
                    if (mVerbose >= 2) {
                        // very verbose
                        System.out.println("//   + Using main activity " + r.activityInfo.name + " (from package " + packageName + ")");
                    }
                    mMainApps.add(new ComponentName(packageName, r.activityInfo.name));
                } else {
                    if (mVerbose >= 3) {
                        // very very verbose
                        System.out.println("//   - NOT USING main activity " + r.activityInfo.name + " (from package " + packageName + ")");
                    }
                }
            }
        }
    } catch (RemoteException e) {
        System.err.println("** Failed talking with package manager!");
        return false;
    }
    if (mMainApps.size() == 0) {
        System.out.println("** No activities found to run, monkey aborted.");
        return false;
    }
    return true;
}
Example 46
Project: Open-Battery-Saver-master  File: BatteryStatsHelper.java View source code
private void processAppUsage(boolean includeZeroConsumption) throws Exception {
    SensorManager sensorManager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
    final int which = mStatsType;
    //final int speedSteps = mPowerProfile.getNumSpeedSteps();
    final int speedSteps = (Integer) mPowerProfile.getClass().getMethod("getNumSpeedSteps").invoke(mPowerProfile);
    final double[] powerCpuNormal = new double[speedSteps];
    final long[] cpuSpeedStepTimes = new long[speedSteps];
    for (int p = 0; p < speedSteps; p++) {
        //powerCpuNormal[p] = mPowerProfile.getAveragePower(PowerProfile.POWER_CPU_ACTIVE, p);
        powerCpuNormal[p] = (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class, int.class).invoke(mPowerProfile, "cpu.active", p);
    }
    final double mobilePowerPerByte = getMobilePowerPerByte();
    final double wifiPowerPerByte = getWifiPowerPerByte();
    //long uSecTime = mStats.computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which);
    long uSecTime = (Long) mStats.getClass().getMethod("computeBatteryRealtime", Long.class, Integer.class).invoke(mStats, SystemClock.elapsedRealtime() * 1000, which);
    long appWakelockTime = 0;
    BatterySipper osApp = null;
    mStatsPeriod = uSecTime;
    //SparseArray<? extends Uid> uidStats = mStats.getUidStats();
    SparseArray<? extends Object> uidStats = (SparseArray<? extends Object>) mStats.getClass().getMethod("getUidStats").invoke(mStats);
    final int NU = uidStats.size();
    for (int iu = 0; iu < NU; iu++) {
        //Uid u = uidStats.valueAt(iu);
        Object u = uidStats.valueAt(iu);
        // in mAs
        double p;
        // in mAs
        double power = 0;
        double highestDrain = 0;
        String packageWithHighestDrain = null;
        //mUsageList.add(new AppUsage(u.getUid(), new double[] {power}));
        //Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
        Map<String, ?> processStats = (Map<String, ?>) u.getClass().getMethod("getProcessStats").invoke(u);
        long cpuTime = 0;
        long cpuFgTime = 0;
        long wakelockTime = 0;
        long gpsTime = 0;
        if (DEBUG)
            Log.i(TAG, "UID " + u.getClass().getMethod("getUid").invoke(u));
        if (processStats.size() > 0) {
            //for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent : processStats.entrySet()) {
            for (Map.Entry<String, ?> ent : processStats.entrySet()) {
                //Uid.Proc ps = ent.getValue();
                Object ps = ent.getValue();
                //final long userTime = ps.getUserTime(which);
                final long userTime = (Long) ps.getClass().getMethod("getUserTime", Integer.class).invoke(ps, which);
                //final long systemTime = ps.getSystemTime(which);
                final long systemTime = (Long) ps.getClass().getMethod("getSystemTime", Integer.class).invoke(ps, which);
                //final long foregroundTime = ps.getForegroundTime(which);
                final long foregroundTime = (Long) ps.getClass().getMethod("getForegroundTime", Integer.class).invoke(ps, which);
                // convert to millis
                cpuFgTime += foregroundTime * 10;
                // convert to millis
                final long tmpCpuTime = (userTime + systemTime) * 10;
                int totalTimeAtSpeeds = 0;
                // Get the total first
                for (int step = 0; step < speedSteps; step++) {
                    //cpuSpeedStepTimes[step] = ps.getTimeAtCpuSpeedStep(step, which);
                    cpuSpeedStepTimes[step] = (Long) ps.getClass().getMethod("getTimeAtCpuSpeedStep", Integer.class, Integer.class).invoke(ps, step, which);
                    totalTimeAtSpeeds += cpuSpeedStepTimes[step];
                }
                if (totalTimeAtSpeeds == 0)
                    totalTimeAtSpeeds = 1;
                // Then compute the ratio of time spent at each speed
                double processPower = 0;
                for (int step = 0; step < speedSteps; step++) {
                    double ratio = (double) cpuSpeedStepTimes[step] / totalTimeAtSpeeds;
                    processPower += ratio * tmpCpuTime * powerCpuNormal[step];
                }
                cpuTime += tmpCpuTime;
                if (DEBUG && processPower != 0) {
                    Log.i(TAG, String.format("process %s, cpu power=%.2f", ent.getKey(), processPower / 1000));
                }
                power += processPower;
                if (packageWithHighestDrain == null || packageWithHighestDrain.startsWith("*")) {
                    highestDrain = processPower;
                    packageWithHighestDrain = ent.getKey();
                } else if (highestDrain < processPower && !ent.getKey().startsWith("*")) {
                    highestDrain = processPower;
                    packageWithHighestDrain = ent.getKey();
                }
            }
        }
        if (cpuFgTime > cpuTime) {
            if (DEBUG && cpuFgTime > cpuTime + 10000) {
                Log.i(TAG, "WARNING! Cputime is more than 10 seconds behind Foreground time");
            }
            // Statistics may not have been gathered yet.
            cpuTime = cpuFgTime;
        }
        power /= 1000;
        if (DEBUG && power != 0)
            Log.i(TAG, String.format("total cpu power=%.2f", power));
        // Process wake lock usage
        //Map<String, ? extends BatteryStats.Uid.Wakelock> wakelockStats = u.getWakelockStats();
        Map<String, ?> wakelockStats = (Map<String, ?>) u.getClass().getMethod("getWakelockStats").invoke(null);
        //for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> wakelockEntry : wakelockStats.entrySet()) {
        for (Map.Entry<String, ?> wakelockEntry : wakelockStats.entrySet()) {
            //Uid.Wakelock wakelock = wakelockEntry.getValue();
            Object wakelock = wakelockEntry.getValue();
            // Only care about partial wake locks since full wake locks
            // are canceled when the user turns the screen off.
            //BatteryStats.Timer timer = wakelock.getWakeTime(BatteryStats.WAKE_TYPE_PARTIAL);
            Object timer = wakelock.getClass().getMethod("getWakeTime", Integer.class).invoke(null, 0);
            if (timer != null) {
                //wakelockTime += timer.getTotalTimeLocked(uSecTime, which);
                wakelockTime += (Long) timer.getClass().getMethod("getTotalTimeLocked", Long.class, Integer.class).invoke(null, uSecTime, which);
            }
        }
        // convert to millis
        wakelockTime /= 1000;
        appWakelockTime += wakelockTime;
        // Add cost of holding a wake lock
        //p = (wakelockTime * mPowerProfile.getAveragePower(PowerProfile.POWER_CPU_AWAKE)) / 1000;
        p = (wakelockTime * (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class).invoke(null, "cpu.awake")) / 1000;
        power += p;
        if (DEBUG && p != 0)
            Log.i(TAG, String.format("wakelock power=%.2f", p));
        // Add cost of mobile traffic
        //final long mobileRx = u.getNetworkActivityCount(NETWORK_MOBILE_RX_BYTES, mStatsType);
        final long mobileRx = (Long) u.getClass().getMethod("getNetworkActivityCount", Integer.class, Integer.class).invoke(null, 0, mStatsType);
        //final long mobileTx = u.getNetworkActivityCount(NETWORK_MOBILE_TX_BYTES, mStatsType);
        final long mobileTx = (Long) u.getClass().getMethod("getNetworkActivityCount", Integer.class, Integer.class).invoke(null, 1, mStatsType);
        p = (mobileRx + mobileTx) * mobilePowerPerByte;
        power += p;
        if (DEBUG && p != 0)
            Log.i(TAG, String.format("mobile power=%.2f", p));
        // Add cost of wifi traffic
        //final long wifiRx = u.getNetworkActivityCount(NETWORK_WIFI_RX_BYTES, mStatsType);
        final long wifiRx = (Long) u.getClass().getMethod("getNetworkActivityCount", Integer.class, Integer.class).invoke(null, 2, mStatsType);
        //final long wifiTx = u.getNetworkActivityCount(NETWORK_WIFI_TX_BYTES, mStatsType);
        final long wifiTx = (Long) u.getClass().getMethod("getNetworkActivityCount", Integer.class, Integer.class).invoke(null, 3, mStatsType);
        p = (wifiRx + wifiTx) * wifiPowerPerByte;
        power += p;
        if (DEBUG && p != 0)
            Log.i(TAG, String.format("wifi power=%.2f", p));
        // Add cost of keeping WIFI running.
        //long wifiRunningTimeMs = u.getWifiRunningTime(uSecTime, which) / 1000;
        long wifiRunningTimeMs = (Long) u.getClass().getMethod("getWifiRunningTime", Long.class, Integer.class).invoke(null, uSecTime, which) / 1000;
        mAppWifiRunning += wifiRunningTimeMs;
        //p = (wifiRunningTimeMs * mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_ON)) / 1000;
        p = (wifiRunningTimeMs * (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class).invoke(null, "wifi.on")) / 1000;
        power += p;
        if (DEBUG && p != 0)
            Log.i(TAG, String.format("wifi running power=%.2f", p));
        // Add cost of WIFI scans
        //long wifiScanTimeMs = u.getWifiScanTime(uSecTime, which) / 1000;
        long wifiScanTimeMs = (Long) u.getClass().getMethod("getWifiScanTime", Long.class, Integer.class).invoke(null, uSecTime, which) / 1000;
        //p = (wifiScanTimeMs * mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_SCAN)) / 1000;
        p = (wifiScanTimeMs * (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class).invoke(null, "wifi.scan")) / 1000;
        power += p;
        if (DEBUG && p != 0)
            Log.i(TAG, String.format("wifi scanning power=%.2f", p));
        //for (int bin = 0; bin < BatteryStats.Uid.NUM_WIFI_BATCHED_SCAN_BINS; bin++) {
        for (int bin = 0; bin < 5; bin++) {
            //long batchScanTimeMs = u.getWifiBatchedScanTime(bin, uSecTime, which) / 1000;
            long batchScanTimeMs = (Long) u.getClass().getMethod("getWifiBatchedScanTime", Integer.class, Long.class, Integer.class).invoke(null, bin, uSecTime, which) / 1000;
            //p = (batchScanTimeMs * mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_BATCHED_SCAN, bin));
            p = (batchScanTimeMs * (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class, Integer.class).invoke(null, "wifi.batchedscan", bin));
            power += p;
            if (DEBUG && p != 0) {
                Log.i(TAG, String.format("wifi batched scanning lvl %d = %.2f", bin, p));
            }
        }
        // Process Sensor usage
        //Map<Integer, ? extends BatteryStats.Uid.Sensor> sensorStats = u.getSensorStats();
        Map<Integer, ?> sensorStats = (Map<Integer, ?>) u.getClass().getMethod("getSensorStats").invoke(null);
        //for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> sensorEntry : sensorStats.entrySet()) {
        for (Map.Entry<Integer, ?> sensorEntry : sensorStats.entrySet()) {
            //Uid.Sensor sensor = sensorEntry.getValue();
            Object sensor = sensorEntry.getValue();
            int sensorHandle = (Integer) sensor.getClass().getMethod("getHandle").invoke(null);
            //BatteryStats.Timer timer = sensor.getSensorTime();
            Object timer = sensor.getClass().getMethod("getSensorTime").invoke(null);
            //long sensorTime = timer.getTotalTimeLocked(uSecTime, which) / 1000;
            long sensorTime = (Long) timer.getClass().getMethod("getTotalTimeLocked", Long.class, Integer.class).invoke(null, uSecTime, which) / 1000;
            double multiplier = 0;
            switch(sensorHandle) {
                //case Uid.Sensor.GPS:
                case -10000:
                    //multiplier = mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_ON);
                    multiplier = (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class).invoke(null, "gps.on");
                    gpsTime = sensorTime;
                    break;
                default:
                    List<Sensor> sensorList = sensorManager.getSensorList(android.hardware.Sensor.TYPE_ALL);
                    for (android.hardware.Sensor s : sensorList) {
                        //if (s.getHandle() == sensorHandle) {
                        int handle = (Integer) s.getClass().getMethod("getHandle").invoke(null);
                        if (handle == sensorHandle) {
                            multiplier = s.getPower();
                            break;
                        }
                    }
            }
            p = (multiplier * sensorTime) / 1000;
            power += p;
            if (DEBUG && p != 0) {
                Log.i(TAG, String.format("sensor %s power=%.2f", sensor.toString(), p));
            }
        }
        if (DEBUG)
            Log.i(TAG, String.format("UID %d total power=%.2f", (Integer) u.getClass().getMethod("getUid").invoke(null), power));
        // Add the app to the list if it is consuming power
        boolean isOtherUser = false;
        //final int userId = UserHandle.getUserId(u.getUid());
        final int userId = (Integer) UserHandle.class.getMethod("getUserId", Integer.class).invoke(null, (Integer) u.getClass().getMethod("getUid").invoke(null));
        if (power != 0 || includeZeroConsumption || (Integer) u.getClass().getMethod("getUid").invoke(null) == 0) {
            BatterySipper app = new BatterySipper(mActivity, mRequestQueue, mHandler, packageWithHighestDrain, DrainType.APP, 0, u, new double[] { power });
            app.cpuTime = cpuTime;
            app.gpsTime = gpsTime;
            app.wifiRunningTime = wifiRunningTimeMs;
            app.cpuFgTime = cpuFgTime;
            app.wakeLockTime = wakelockTime;
            app.mobileRxBytes = mobileRx;
            app.mobileTxBytes = mobileTx;
            app.wifiRxBytes = wifiRx;
            app.wifiTxBytes = wifiTx;
            //if ((Integer) u.getClass().getMethod("getUid").invoke(null) == Process.WIFI_UID) {
            if ((Integer) u.getClass().getMethod("getUid").invoke(null) == 1010) {
                mWifiSippers.add(app);
            //} else if ((Integer) u.getClass().getMethod("getUid").invoke(null) == Process.BLUETOOTH_UID) {
            } else if ((Integer) u.getClass().getMethod("getUid").invoke(null) == 1002) {
                mBluetoothSippers.add(app);
            //} else if (userId != UserHandle.myUserId()
            } else if (userId != (Integer) UserHandle.class.getMethod("myUserId").invoke(null) && //&& UserHandle.getAppId((Integer) u.getClass().getMethod("getUid").invoke(null)) >= Process.FIRST_APPLICATION_UID) {
            (Integer) UserHandle.class.getMethod("getAppId", Integer.class).invoke(null, (Integer) u.getClass().getMethod("getUid").invoke(null)) >= Process.FIRST_APPLICATION_UID) {
                isOtherUser = true;
                List<BatterySipper> list = mUserSippers.get(userId);
                if (list == null) {
                    list = new ArrayList<BatterySipper>();
                    mUserSippers.put(userId, list);
                }
                list.add(app);
            } else {
                mUsageList.add(app);
            }
            if ((Integer) u.getClass().getMethod("getUid").invoke(null) == 0) {
                osApp = app;
            }
        }
        if (power != 0 || includeZeroConsumption) {
            //if ((Integer) u.getClass().getMethod("getUid").invoke(null) == Process.WIFI_UID) {
            if ((Integer) u.getClass().getMethod("getUid").invoke(null) == 1010) {
                mWifiPower += power;
            //} else if ((Integer) u.getClass().getMethod("getUid").invoke(null) == Process.BLUETOOTH_UID) {
            } else if ((Integer) u.getClass().getMethod("getUid").invoke(null) == 1002) {
                mBluetoothPower += power;
            } else if (isOtherUser) {
                Double userPower = mUserPower.get(userId);
                if (userPower == null) {
                    userPower = power;
                } else {
                    userPower += power;
                }
                mUserPower.put(userId, userPower);
            } else {
                if (power > mMaxPower)
                    mMaxPower = power;
                mTotalPower += power;
            }
        }
    }
    // this remainder to the OS, if possible.
    if (osApp != null) {
        //long wakeTimeMillis = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, which) / 1000;
        long wakeTimeMillis = (Long) mStats.getClass().getMethod("computeBatteryUptime", Long.class, Integer.class).invoke(null, SystemClock.uptimeMillis() * 1000, which) / 1000;
        //wakeTimeMillis -= appWakelockTime + (mStats.getScreenOnTime(SystemClock.elapsedRealtime(), which) / 1000);
        wakeTimeMillis -= appWakelockTime + ((Long) mStats.getClass().getMethod("getScreenOnTime", Long.class, Integer.class).invoke(null, SystemClock.elapsedRealtime(), which) / 1000);
        if (wakeTimeMillis > 0) {
            //double power = (wakeTimeMillis * mPowerProfile.getAveragePower(PowerProfile.POWER_CPU_AWAKE)) / 1000;
            double power = (wakeTimeMillis * (Double) mPowerProfile.getClass().getMethod("getAveragePower", String.class).invoke(null, "cpu.awake")) / 1000;
            if (DEBUG)
                Log.i(TAG, "OS wakeLockTime " + wakeTimeMillis + " power " + power);
            osApp.wakeLockTime += wakeTimeMillis;
            osApp.value += power;
            osApp.values[0] += power;
            if (osApp.value > mMaxPower)
                mMaxPower = osApp.value;
            mTotalPower += power;
        }
    }
}
Example 47
Project: XPrivacy-master  File: Util.java View source code
@SuppressLint("NewApi")
public static int getAppId(int uid) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        try {
            // UserHandle: public static final int getAppId(int uid)
            Method method = (Method) UserHandle.class.getDeclaredMethod("getAppId", int.class);
            uid = (Integer) method.invoke(null, uid);
        } catch (Throwable ex) {
            Util.log(null, Log.WARN, ex.toString());
        }
    return uid;
}
Example 48
Project: AppOpsControl-master  File: Utils.java View source code
/* Used by UserSettings as well. Call this on a non-ui thread. */
public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
    Uri contactUri = Profile.CONTENT_URI;
    InputStream avatarDataStream = Contacts.openContactPhotoInputStream(context.getContentResolver(), contactUri, true);
    // If there's no profile photo, assign a default avatar
    if (avatarDataStream == null) {
        return false;
    }
    int userId = user != null ? user.id : UserHandle.myUserId();
    UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
    Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
    um.setUserIcon(userId, icon);
    try {
        avatarDataStream.close();
    } catch (IOException ioe) {
    }
    return true;
}
Example 49
Project: platform_packages_providers_downloadprovider-master  File: Helpers.java View source code
/**
     * Schedule (or reschedule) a job for the given {@link DownloadInfo} using
     * its current state to define job constraints.
     */
public static boolean scheduleJob(Context context, DownloadInfo info) {
    if (info == null)
        return false;
    final JobScheduler scheduler = context.getSystemService(JobScheduler.class);
    // Tear down any existing job for this download
    final int jobId = (int) info.mId;
    scheduler.cancel(jobId);
    // Skip scheduling if download is paused or finished
    if (!info.isReadyToSchedule())
        return false;
    final JobInfo.Builder builder = new JobInfo.Builder(jobId, new ComponentName(context, DownloadJobService.class));
    // priority, since it's effectively a foreground service
    if (info.isVisible()) {
        builder.setPriority(JobInfo.PRIORITY_FOREGROUND_APP);
        builder.setFlags(JobInfo.FLAG_WILL_BE_FOREGROUND);
    }
    // We might have a backoff constraint due to errors
    final long latency = info.getMinimumLatency();
    if (latency > 0) {
        builder.setMinimumLatency(latency);
    }
    // We always require a network, but the type of network might be further
    // restricted based on download request or user override
    builder.setRequiredNetworkType(info.getRequiredNetworkType(info.mTotalBytes));
    if ((info.mFlags & FLAG_REQUIRES_CHARGING) != 0) {
        builder.setRequiresCharging(true);
    }
    if ((info.mFlags & FLAG_REQUIRES_DEVICE_IDLE) != 0) {
        builder.setRequiresDeviceIdle(true);
    }
    // If package name was filtered during insert (probably due to being
    // invalid), blame based on the requesting UID instead
    String packageName = info.mPackage;
    if (packageName == null) {
        packageName = context.getPackageManager().getPackagesForUid(info.mUid)[0];
    }
    scheduler.scheduleAsPackage(builder.build(), packageName, UserHandle.myUserId(), TAG);
    return true;
}
Example 50
Project: platform_packages_providers_telephonyprovider-master  File: TelephonyProvider.java View source code
@Override
public synchronized Uri insert(Uri url, ContentValues initialValues) {
    Uri result = null;
    int subId = SubscriptionManager.getDefaultSubscriptionId();
    checkPermission();
    SQLiteDatabase db = getWritableDatabase();
    int match = s_urlMatcher.match(url);
    boolean notify = false;
    switch(match) {
        case URL_TELEPHONY_USING_SUBID:
            {
                String subIdString = url.getLastPathSegment();
                try {
                    subId = Integer.parseInt(subIdString);
                } catch (NumberFormatException e) {
                    loge("NumberFormatException" + e);
                    return result;
                }
                if (DBG)
                    log("subIdString = " + subIdString + " subId = " + subId);
            }
        case URL_TELEPHONY:
            {
                ContentValues values;
                if (initialValues != null) {
                    values = new ContentValues(initialValues);
                } else {
                    values = new ContentValues();
                }
                values = DatabaseHelper.setDefaultValue(values);
                if (!values.containsKey(EDITED)) {
                    values.put(EDITED, USER_EDITED);
                }
                try {
                    // Replace on conflict so that if same APN is present in db with edited
                    // as UNEDITED or USER/CARRIER_DELETED, it is replaced with
                    // edited USER/CARRIER_EDITED
                    long rowID = db.insertWithOnConflict(CARRIERS_TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                    if (rowID >= 0) {
                        result = ContentUris.withAppendedId(CONTENT_URI, rowID);
                        notify = true;
                    }
                    if (VDBG)
                        log("insert: inserted " + values.toString() + " rowID = " + rowID);
                } catch (SQLException e) {
                    log("insert: exception " + e);
                    Cursor oldRow = DatabaseHelper.selectConflictingRow(db, CARRIERS_TABLE, values);
                    if (oldRow != null) {
                        ContentValues mergedValues = new ContentValues();
                        DatabaseHelper.mergeFieldsAndUpdateDb(db, CARRIERS_TABLE, oldRow, values, mergedValues, false, getContext());
                        oldRow.close();
                        notify = true;
                    }
                }
                break;
            }
        case URL_CURRENT_USING_SUBID:
            {
                String subIdString = url.getLastPathSegment();
                try {
                    subId = Integer.parseInt(subIdString);
                } catch (NumberFormatException e) {
                    loge("NumberFormatException" + e);
                    return result;
                }
                if (DBG)
                    log("subIdString = " + subIdString + " subId = " + subId);
            // FIXME use subId in the query
            }
        case URL_CURRENT:
            {
                // zero out the previous operator
                db.update(CARRIERS_TABLE, s_currentNullMap, CURRENT + "!=0", null);
                String numeric = initialValues.getAsString(NUMERIC);
                int updated = db.update(CARRIERS_TABLE, s_currentSetMap, NUMERIC + " = '" + numeric + "'", null);
                if (updated > 0) {
                    if (VDBG)
                        log("Setting numeric '" + numeric + "' to be the current operator");
                } else {
                    loge("Failed setting numeric '" + numeric + "' to the current operator");
                }
                break;
            }
        case URL_PREFERAPN_USING_SUBID:
        case URL_PREFERAPN_NO_UPDATE_USING_SUBID:
            {
                String subIdString = url.getLastPathSegment();
                try {
                    subId = Integer.parseInt(subIdString);
                } catch (NumberFormatException e) {
                    loge("NumberFormatException" + e);
                    return result;
                }
                if (DBG)
                    log("subIdString = " + subIdString + " subId = " + subId);
            }
        case URL_PREFERAPN:
        case URL_PREFERAPN_NO_UPDATE:
            {
                if (initialValues != null) {
                    if (initialValues.containsKey(COLUMN_APN_ID)) {
                        setPreferredApnId(initialValues.getAsLong(COLUMN_APN_ID), subId);
                    }
                }
                break;
            }
        case URL_SIMINFO:
            {
                long id = db.insert(SIMINFO_TABLE, null, initialValues);
                result = ContentUris.withAppendedId(SubscriptionManager.CONTENT_URI, id);
                break;
            }
    }
    if (notify) {
        getContext().getContentResolver().notifyChange(CONTENT_URI, null, true, UserHandle.USER_ALL);
    }
    return result;
}
Example 51
Project: robolectric-master  File: DefaultPackageManager.java View source code
@Override
public PackageInstaller getPackageInstaller() {
    if (packageInstaller == null) {
        if (RuntimeEnvironment.getApiLevel() == VERSION_CODES.O) {
            packageInstaller = new PackageInstaller(ReflectionHelpers.createNullProxy(IPackageInstaller.class), null, UserHandle.myUserId());
        } else {
            packageInstaller = ReflectionHelpers.callConstructor(PackageInstaller.class, ClassParameter.from(Context.class, RuntimeEnvironment.application), ClassParameter.from(PackageManager.class, this), ClassParameter.from(IPackageInstaller.class, ReflectionHelpers.createNullProxy(IPackageInstaller.class)), ClassParameter.from(String.class, null), ClassParameter.from(int.class, UserHandle.myUserId()));
        }
    }
    return packageInstaller;
}
Example 52
Project: AndroidChromium-master  File: ChromeBrowserProvider.java View source code
@SuppressLint("NewApi")
private void notifyChange(final Uri uri) {
    // devices whose API level is less than API 17.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        UserHandle callingUserHandle = Binder.getCallingUserHandle();
        if (callingUserHandle != null && !callingUserHandle.equals(android.os.Process.myUserHandle())) {
            ThreadUtils.postOnUiThread(new Runnable() {

                @Override
                public void run() {
                    getContext().getContentResolver().notifyChange(uri, null);
                }
            });
            return;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
}
Example 53
Project: ifexplorer-master  File: StorageUtil.java View source code
public static String getHomeDir() {
    if (IfConfig.PRODUCT_ROCK_CHIP) {
        return "/sdcard";
    }
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        int id = 0;
        try {
            Class<?> class_UserHandle = null;
            try {
                class_UserHandle = Class.forName("android.os.UserHandle");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (class_UserHandle != null) {
                Method method_myUserId = class_UserHandle.getMethod("myUserId", new Class[] {});
                try {
                    id = (Integer) method_myUserId.invoke(class_UserHandle, new Object[] {});
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return "/storage/emulated/" + id;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return "/sdcard";
        }
    } else {
        return "/sdcard";
    }
}
Example 54
Project: droidel-master  File: ActivityThread.java View source code
public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo, int flags) {
    boolean includeCode = (flags & Context.CONTEXT_INCLUDE_CODE) != 0;
    boolean securityViolation = includeCode && ai.uid != 0 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid) : true);
    if ((flags & (Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY)) == Context.CONTEXT_INCLUDE_CODE) {
        if (securityViolation) {
            String msg = "Requesting code from " + ai.packageName + " (with uid " + ai.uid + ")";
            if (mBoundApplication != null) {
                msg = msg + " to be run in process " + mBoundApplication.processName + " (with uid " + mBoundApplication.appInfo.uid + ")";
            }
            throw new SecurityException(msg);
        }
    }
    return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
}
Example 55
Project: ApkChannelPackage-master  File: PackageParser.java View source code
private static boolean copyNeeded(int flags, Package p, PackageUserState state, Bundle metaData, int userId) {
    if (userId != UserHandle.USER_SYSTEM) {
        // to fix up the uid.
        return true;
    }
    if (state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
        boolean enabled = state.enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
        if (p.applicationInfo.enabled != enabled) {
            return true;
        }
    }
    boolean suspended = (p.applicationInfo.flags & FLAG_SUSPENDED) != 0;
    if (state.suspended != suspended) {
        return true;
    }
    if (!state.installed || state.hidden) {
        return true;
    }
    if (state.stopped) {
        return true;
    }
    if ((flags & PackageManager.GET_META_DATA) != 0 && (metaData != null || p.mAppMetaData != null)) {
        return true;
    }
    if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0 && p.usesLibraryFiles != null) {
        return true;
    }
    return false;
}
Example 56
Project: CompositeAndroid-master  File: ActivityPlugin.java View source code
public void sendOrderedBroadcastAsUser(final Intent intent, final UserHandle user, final String receiverPermission, final BroadcastReceiver resultReceiver, final Handler scheduler, final int initialCode, final String initialData, final Bundle initialExtras) {
    verifyMethodCalledFromDelegate("sendOrderedBroadcastAsUser(Intent, UserHandle, String, BroadcastReceiver, Handler, Integer, String, Bundle)");
    ((CallVoid8<Intent, UserHandle, String, BroadcastReceiver, Handler, Integer, String, Bundle>) mSuperListeners.pop()).call(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
Example 57
Project: Brevent-master  File: HideApiOverrideN.java View source code
private static int getUserSystem() {
    try {
        return UserHandle.USER_SYSTEM;
    } catch (LinkageError e) {
        Log.w(TAG, "Can't find UserHandle.USER_SYSTEM");
        return 0;
    }
}
Example 58
Project: find-sec-bugs-master  File: ContextWrapper.java View source code
@Override
public void sendBroadcastAsUser(Intent intent, UserHandle user) {
}
Example 59
Project: DroidPlugin-master  File: UserHandleCompat.java View source code
//    UserHandle.getCallingUserId()
public static int getCallingUserId() {
    try {
        return (int) MethodUtils.invokeStaticMethod(UserHandle.class, "getCallingUserId");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}
Example 60
Project: pluginframework-master  File: UserHandleCompat.java View source code
//    UserHandle.getCallingUserId()
public static int getCallingUserId() {
    try {
        return (int) MethodUtils.invokeStaticMethod(UserHandle.class, "getCallingUserId");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}
Example 61
Project: piwik_android_sdk-master  File: FullEnvPackageManager.java View source code
@Override
public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) {
    return null;
}
Example 62
Project: premiumer-master  File: PackageManagerStub.java View source code
@Override
public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) {
    return null;
}
Example 63
Project: ASecure-master  File: Settings.java View source code
/**
         * Convenience function for updating a single settings value as an
         * integer. This will either create a new entry in the table if the
         * given name does not exist, or modify the value of the existing row
         * with that name.  Note that internally setting values are always
         * stored as strings, so this function converts the given value to a
         * string before storing it.
         *
         * @param cr The ContentResolver to access.
         * @param name The name of the setting to modify.
         * @param value The new value for the setting.
         * @return true if the value was set, false on database errors
         */
public static boolean putInt(ContentResolver cr, String name, int value) {
    //putIntForUser(cr, name, value, UserHandle.myUserId());
    return false;
}
Example 64
Project: AndroidBaseUtils-master  File: ContextUtil.java View source code
@TargetApi(17)
public static void sendBroadcastAsUser(Intent intent, UserHandle user) {
    Base.getContext().sendBroadcastAsUser(intent, user);
}
Example 65
Project: device_falcon_umts_kk-master  File: FMRecordingService.java View source code
private void sendRecordingStatusIntent(int status) {
    Intent intent = new Intent(ACTION_FM_RECORDING_STATUS);
    intent.putExtra("state", status);
    Log.d(TAG, "posting intent for FM Recording status as = " + status);
    getApplicationContext().sendBroadcastAsUser(intent, UserHandle.ALL);
}