Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2006 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.android.settings.applications;
 
 
 
 
 final class CanBeOnSdCardChecker {
     final IPackageManager mPm;
     int mInstallLocation;
     
     CanBeOnSdCardChecker() {
          = IPackageManager.Stub.asInterface(
                 ServiceManager.getService("package"));
     }
     
     void init() {
         try {
              = .getInstallLocation();
         } catch (RemoteException e) {
             Log.e("CanBeOnSdCardChecker""Is Package Manager running?");
             return;
         }
     }
     
     boolean check(ApplicationInfo info) {
         boolean canBe = false;
         if ((info.flags & .) != 0) {
             canBe = true;
         } else {
             if ((info.flags & .) == 0 &&
                     (info.flags & .) == 0) {
                 if (info.installLocation == . ||
                         info.installLocation == .) {
                     canBe = true;
                 } else if (info.installLocation
                         == .) {
                     if ( == .) {
                         // For apps with no preference and the default value set
                         // to install on sdcard.
                         canBe = true;
                     }
                 }
             }
        }
        return canBe;
    }
Activity to pick an application that will be used to display installation information and options to uninstall/delete user data for system applications. This activity can be launched through Settings or via the ACTION_MANAGE_PACKAGE_STORAGE intent.
public class ManageApplications extends TabActivity implements
    static final String TAG = "ManageApplications";
    static final boolean DEBUG = false;
    
    // attributes used as keys when passing values to InstalledAppDetails activity
    public static final String APP_CHG = "chg";
    
    // constant value that can be used to check return code from sub activity.
    private static final int INSTALLED_APP_DETAILS = 1;
    // sort order that can be changed through the menu can be sorted alphabetically
    // or size(descending)
    private static final int MENU_OPTIONS_BASE = 0;
    // Filter options used for displayed list of applications
    public static final int FILTER_APPS_ALL =  + 0;
    public static final int FILTER_APPS_THIRD_PARTY =  + 1;
    public static final int FILTER_APPS_SDCARD =  + 2;
    public static final int SORT_ORDER_ALPHA =  + 4;
    public static final int SORT_ORDER_SIZE =  + 5;
    public static final int SHOW_RUNNING_SERVICES =  + 6;
    public static final int SHOW_BACKGROUND_PROCESSES =  + 7;
    // sort order
    private int mSortOrder = ;
    // Filter value
    private int mFilterApps = ;
    
    
    // Size resource used for packages whose size computation failed for some reason
    private CharSequence mInvalidSizeStr;
    
    // layout inflater object used to inflate views
    private LayoutInflater mInflater;
    
    private String mCurrentPkgName;
    
    private View mLoadingContainer;
    private View mListContainer;
    // ListView used to display list
    private ListView mListView;
    // Custom view used to display running processes
    
    // These are for keeping track of activity and tab switch state.
    private int mCurView;
    private boolean mCreatedRunning;
    private boolean mResumedRunning;
    private boolean mActivityResumed;
    private Object mNonConfigInstance;
    
    private StatFs mDataFileStats;
    private StatFs mSDCardFileStats;
    private boolean mLastShowedInternalStorage = true;
    final Runnable mRunningProcessesAvail = new Runnable() {
        public void run() {
            handleRunningProcessesAvail();
        }
    };
    // View Holder used when displaying views
    static class AppViewHolder {
        TextView appName;
        ImageView appIcon;
        TextView appSize;
        TextView disabled;
        CheckBox checkBox;
        
        void updateSizeText(ManageApplications ma) {
            if () Log.i("updateSizeText of " + . + " " + 
                    + ": " + .);
            if (. != null) {
                .setText(.);
            } else if (. == .) {
                .setText(ma.mInvalidSizeStr);
            }
        }
    }
    
    /*
     * Custom adapter implementation for the ListView
     * This adapter maintains a map for each displayed application and its properties
     * An index value on each AppInfo object indicates the correct position or index
     * in the list. If the list gets updated dynamically when the user is viewing the list of
     * applications, we need to return the correct index of position. This is done by mapping
     * the getId methods via the package name into the internal maps and indices.
     * The order of applications in the list is mirrored in mAppLocalList
     */
    class ApplicationsAdapter extends BaseAdapter implements Filterable,
        private final ApplicationsState mState;
        private final ArrayList<ViewmActive = new ArrayList<View>();
        private ArrayList<ApplicationsState.AppEntrymEntries;
        private boolean mResumed;
        private int mLastFilterMode=-1, mLastSortMode=-1;
        private boolean mWaitingForData;
        private Filter mFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                ArrayList<ApplicationsState.AppEntryentries
                        = applyPrefixFilter(constraint);
                FilterResults fr = new FilterResults();
                fr.values = entries;
                fr.count = entries.size();
                return fr;
            }
            @Override
            protected void publishResults(CharSequence constraintFilterResults results) {
                 = constraint;
                 = (ArrayList<ApplicationsState.AppEntry>)results.values;
                notifyDataSetChanged();
                updateStorageUsage();
            }
        };
        public ApplicationsAdapter(ApplicationsState state) {
             = state;
        }
        public void resume(int filterint sort) {
            if () Log.i("Resume!  mResumed=" + );
            if (!) {
                 = true;
                .resume(this);
                 = filter;
                 = sort;
                rebuild(true);
            } else {
                rebuild(filtersort);
            }
        }
        public void pause() {
            if () {
                 = false;
                .pause();
            }
        }
        public void rebuild(int filterint sort) {
            if (filter ==  && sort == ) {
                return;
            }
             = filter;
             = sort;
            rebuild(true);
        }
        
        public void rebuild(boolean eraseold) {
            if () Log.i("Rebuilding app list...");
            ApplicationsState.AppFilter filterObj;
            Comparator<AppEntrycomparatorObj;
            switch () {
                case :
                    filterObj = .;
                    break;
                case :
                    filterObj = .;
                    break;
                default:
                    filterObj = null;
                    break;
            }
            switch () {
                case :
                    comparatorObj = .;
                    break;
                default:
                    comparatorObj = .;
                    break;
            }
            ArrayList<ApplicationsState.AppEntryentries
                    = .rebuild(filterObjcomparatorObj);
            if (entries == null && !eraseold) {
                // Don't have new list yet, but can continue using the old one.
                return;
            }
             = entries;
            if ( != null) {
                 = applyPrefixFilter();
            } else {
                 = null;
            }
            notifyDataSetChanged();
            updateStorageUsage();
            if (entries == null) {
                 = true;
                .setVisibility(.);
                .setVisibility(.);
            } else {
                .setVisibility(.);
                .setVisibility(.);
            }
        }
                ArrayList<ApplicationsState.AppEntryorigEntries) {
            if (prefix == null || prefix.length() == 0) {
                return origEntries;
            } else {
                String prefixStr = ApplicationsState.normalize(prefix.toString());
                final String spacePrefixStr = " " + prefixStr;
                ArrayList<ApplicationsState.AppEntrynewEntries
                        = new ArrayList<ApplicationsState.AppEntry>();
                for (int i=0; i<origEntries.size(); i++) {
                    ApplicationsState.AppEntry entry = origEntries.get(i);
                    String nlabel = entry.getNormalizedLabel();
                    if (nlabel.startsWith(prefixStr) || nlabel.indexOf(spacePrefixStr) != -1) {
                        newEntries.add(entry);
                    }
                }
                return newEntries;
            }
        }
        @Override
        public void onRunningStateChanged(boolean running) {
            setProgressBarIndeterminateVisibility(running);
        }
        @Override
        public void onRebuildComplete(ArrayList<AppEntryapps) {
            if (.getVisibility() == .) {
                .startAnimation(AnimationUtils.loadAnimation(
                        ManageApplications.this, android.R.anim.fade_out));
                .startAnimation(AnimationUtils.loadAnimation(
                        ManageApplications.this, android.R.anim.fade_in));
            }
            .setVisibility(.);
            .setVisibility(.);
             = false;
             = apps;
            notifyDataSetChanged();
            updateStorageUsage();
        }
        @Override
        public void onPackageListChanged() {
            rebuild(false);
        }
        @Override
        public void onPackageIconChanged() {
            // We ensure icons are loaded when their item is displayed, so
            // don't care about icons loaded in the background.
        }
        @Override
        public void onPackageSizeChanged(String packageName) {
            for (int i=0; i<.size(); i++) {
                AppViewHolder holder = (AppViewHolder).get(i).getTag();
                if (holder.entry.info.packageName.equals(packageName)) {
                    synchronized (holder.entry) {
                        holder.updateSizeText(ManageApplications.this);
                    }
                    if (holder.entry.info.packageName.equals()
                            &&  == ) {
                        // We got the size information for the last app the
                        // user viewed, and are sorting by size...  they may
                        // have cleared data, so we immediately want to resort
                        // the list with the new size to reflect it to the user.
                        rebuild(false);
                    }
                    updateStorageUsage();
                    return;
                }
            }
        }
        @Override
        public void onAllSizesComputed() {
            if ( == ) {
                rebuild(false);
            }
        }
        
        public int getCount() {
            return  != null ? .size() : 0;
        }
        
        public Object getItem(int position) {
            return .get(position);
        }
        
        public ApplicationsState.AppEntry getAppEntry(int position) {
            return .get(position);
        }
        public long getItemId(int position) {
            return .get(position).;
        }
        
        public View getView(int positionView convertViewViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unnecessary calls
            // to findViewById() on each row.
            AppViewHolder holder;
            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = .inflate(..null);
                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new AppViewHolder();
                holder.appName = (TextViewconvertView.findViewById(..);
                holder.appIcon = (ImageViewconvertView.findViewById(..);
                holder.appSize = (TextViewconvertView.findViewById(..);
                holder.disabled = (TextViewconvertView.findViewById(..);
                holder.checkBox = (CheckBoxconvertView.findViewById(..);
                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (AppViewHolderconvertView.getTag();
            }
            // Bind the data efficiently with the holder
            ApplicationsState.AppEntry entry = .get(position);
            synchronized (entry) {
                holder.entry = entry;
                if (entry.label != null) {
                    holder.appName.setText(entry.label);
                    holder.appName.setTextColor(getResources().getColorStateList(
                            entry.info.enabled ? android.R.color.primary_text_dark
                                    : android.R.color.secondary_text_dark));
                }
                .ensureIcon(entry);
                if (entry.icon != null) {
                    holder.appIcon.setImageDrawable(entry.icon);
                }
                holder.updateSizeText(ManageApplications.this);
                if (.) {
                    holder.disabled.setVisibility(entry.info.enabled ? . : .);
                } else {
                    holder.disabled.setVisibility(.);
                }
                if ( == ) {
                    holder.checkBox.setVisibility(.);
                    holder.checkBox.setChecked((entry.info.flags
                            & .) != 0);
                } else {
                    holder.checkBox.setVisibility(.);
                }
            }
            .remove(convertView);
            .add(convertView);
            return convertView;
        }
        @Override
        public Filter getFilter() {
            return ;
        }
        @Override
        public void onMovedToScrapHeap(View view) {
            .remove(view);
        }
    }
    
    static final String TAB_DOWNLOADED = "Downloaded";
    static final String TAB_RUNNING = "Running";
    static final String TAB_ALL = "All";
    static final String TAB_SDCARD = "OnSdCard";
    private View mRootView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         = ApplicationsState.getInstance(getApplication());
        Intent intent = getIntent();
        String action = intent.getAction();
        String defaultTabTag = ;
        if (intent.getComponent().getClassName().equals(
                "com.android.settings.RunningServices")) {
            defaultTabTag = ;
        } else if (intent.getComponent().getClassName().equals(
                "com.android.settings.applications.StorageUse")
                || action.equals(.)) {
             = ;
             = ;
            defaultTabTag = ;
        } else if (action.equals(.)) {
            // Select the all-apps tab, with the default sorting
            defaultTabTag = ;
        }
        
        if (savedInstanceState != null) {
             = savedInstanceState.getInt("sortOrder");
             = savedInstanceState.getInt("filterApps");
            String tmp = savedInstanceState.getString("defaultTabTag");
            if (tmp != nulldefaultTabTag = tmp;
        }
        
        
         = new StatFs("/data");
         = new StatFs(Environment.getExternalStorageDirectory().toString());
        // initialize some window features
        // initialize the inflater
        // Create adapter and list view here
        ListView lv = (ListView.findViewById(android.R.id.list);
        View emptyView = .findViewById(.....);
        if (emptyView != null) {
            lv.setEmptyView(emptyView);
        }
        lv.setOnItemClickListener(this);
        lv.setSaveEnabled(true);
        lv.setItemsCanFocus(true);
        lv.setOnItemClickListener(this);
        lv.setTextFilterEnabled(true);
         = lv;
                ..);
        final TabHost tabHost = getTabHost();
        tabHost.addTab(tabHost.newTabSpec()
                .setIndicator(getString(..),
                        getResources().getDrawable(..))
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec()
                .setIndicator(getString(..),
                        getResources().getDrawable(..))
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec()
                .setIndicator(getString(..),
                        getResources().getDrawable(..))
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec()
                .setIndicator(getString(..),
                        getResources().getDrawable(..))
                .setContent(this));
        tabHost.setCurrentTabByTag(defaultTabTag);
        tabHost.setOnTabChangedListener(this);
    }
    
    @Override
    public void onStart() {
        super.onStart();
    }
    @Override
    protected void onResume() {
        super.onResume();
         = true;
        showCurrentTab();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("sortOrder");
        outState.putInt("filterApps");
        outState.putString("defautTabTag"getTabHost().getCurrentTabTag());
    }
    @Override
    }
    
    @Override
    protected void onPause() {
        super.onPause();
         = false;
        .pause();
        if () {
            .doPause();
             = false;
        }
    }
    @Override
    protected void onActivityResult(int requestCodeint resultCode,
            Intent data) {
        if (requestCode ==  &&  != null) {
        }
    }
    
    // utility method used to start sub activity
    private void startApplicationDetailsActivity() {
        // Create intent to start new activity
                Uri.fromParts("package"null));
        // start new activity to display extended information
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, , 1, ..)
                .setIcon(android.R.drawable.ic_menu_sort_alphabetically);
        menu.add(0, , 2, ..)
                .setIcon(android.R.drawable.ic_menu_sort_by_size); 
        menu.add(0, , 3, ..);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        /*
         * The running processes screen doesn't use the mApplicationsAdapter
         * so bringing up this menu in that case doesn't make any sense.
         */
        if ( == ) {
            boolean showingBackground = ..getShowBackground();
            menu.findItem().setVisible(false);
            menu.findItem().setVisible(false);
            menu.findItem().setVisible(showingBackground);
            menu.findItem().setVisible(!showingBackground);
        } else {
            menu.findItem().setVisible( != );
            menu.findItem().setVisible(false);
            menu.findItem().setVisible(false);
        }
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int menuId = item.getItemId();
        if ((menuId == ) || (menuId == )) {
             = menuId;
            if ( != ) {
                .rebuild();
            }
        } else if (menuId == ) {
            ..setShowBackground(false);
        } else if (menuId == ) {
            ..setShowBackground(true);
        }
        return true;
    }
    
    @Override
    public boolean onKeyUp(int keyCodeKeyEvent event) {
        if (keyCode == . && event.isTracking()) {
            if ( != ) {
                        .showSoftInputUnchecked(0, null);
            }
            return true;
        }
        return super.onKeyUp(keyCodeevent);
    }
    public void onItemClick(AdapterView<?> parentView viewint position,
            long id) {
        ApplicationsState.AppEntry entry = .getAppEntry(position);
         = entry.info.packageName;
    }
    
    // Finish the activity if the user presses the back button to cancel the activity
    public void onCancel(DialogInterface dialog) {
        finish();
    }
    public View createTabContent(String tag) {
        return ;
    }
    static final int VIEW_NOTHING = 0;
    static final int VIEW_LIST = 1;
    static final int VIEW_RUNNING = 2;
    void updateStorageUsage() {
        if ( == ) {
            return;
        }
        long freeStorage = 0;
        long appStorage = 0;
        long totalStorage = 0;
        CharSequence newLabel = null;
        if ( == ) {
            if () {
                 = false;
            }
            newLabel = this.getText(..);
            .restat(Environment.getExternalStorageDirectory().toString());
            try {
                totalStorage = (long).getBlockCount() *
                        .getBlockSize();
                freeStorage = (long.getAvailableBlocks() *
                .getBlockSize();
            } catch (IllegalArgumentException e) {
                // use the old value of mFreeMem
            }
        } else {
            if (!) {
                 = true;
            }
            newLabel = this.getText(..);
            .restat("/data");
            try {
                totalStorage = (long).getBlockCount() *
                        .getBlockSize();
                freeStorage = (long.getAvailableBlocks() *
                    .getBlockSize();
            } catch (IllegalArgumentException e) {
            }
            final int N = .getCount();
            for (int i=0; i<Ni++) {
                ApplicationsState.AppEntry ae = .getAppEntry(i);
                appStorage += ae.codeSize + ae.dataSize;
            }
            freeStorage += .sumCacheSizes();
        }
        if (newLabel != null) {
            .setText(newLabel);
        }
        if (totalStorage > 0) {
            .setRatios((totalStorage-freeStorage-appStorage)/(float)totalStorage,
                    appStorage/(float)totalStoragefreeStorage/(float)totalStorage);
            long usedStorage = totalStorage - freeStorage;
            if ( != usedStorage) {
                 = usedStorage;
                String sizeStr = Formatter.formatShortFileSize(thisusedStorage);
                .setText(getResources().getString(
                        ..sizeStr));
            }
            if ( != freeStorage) {
                 = freeStorage;
                String sizeStr = Formatter.formatShortFileSize(thisfreeStorage);
                .setText(getResources().getString(
                        ..sizeStr));
            }
        } else {
            .setRatios(0, 0, 0);
            if ( != -1) {
                 = -1;
                .setText("");
            }
            if ( != -1) {
                 = -1;
                .setText("");
            }
        }
    }
    private void selectView(int which) {
        if (which == ) {
            if () {
                .doPause();
                 = false;
            }
            if ( != which) {
                .setVisibility(.);
                .setVisibility(.);
                .setVisibility(.);
            }
            if () {
                .resume();
            }
        } else if (which == ) {
            if (!) {
                .doCreate(null);
                 = true;
            }
            boolean haveData = true;
            if ( && !) {
                haveData = .doResume();
                 = true;
            }
            .pause();
            if ( != which) {
                if (haveData) {
                    .setVisibility(.);
                } else {
                    .setVisibility(.);
                }
                .setVisibility(.);
            }
        }
         = which;
    }
        if ( == ) {
            .startAnimation(AnimationUtils.loadAnimation(
                    this, android.R.anim.fade_out));
            .startAnimation(AnimationUtils.loadAnimation(
                    this, android.R.anim.fade_in));
            .setVisibility(.);
        }
    }
    public void showCurrentTab() {
        String tabId = getTabHost().getCurrentTabTag();
        int newOption;
        if (.equalsIgnoreCase(tabId)) {
            newOption = ;
        } else if (.equalsIgnoreCase(tabId)) {
            newOption = ;
        } else if (.equalsIgnoreCase(tabId)) {
            newOption = ;
        } else if (.equalsIgnoreCase(tabId)) {
                    .hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            selectView();
            return;
        } else {
            // Invalid option. Do nothing
            return;
        }
        
         = newOption;
        selectView();
        updateStorageUsage();
    }
    public void onTabChanged(String tabId) {
        showCurrentTab();
    }
New to GrepCode? Check out our FAQ X