1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.supportv4.app; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.content.IntentFilter; 23 import android.content.pm.ActivityInfo; 24 import android.content.pm.ApplicationInfo; 25 import android.content.pm.PackageManager; 26 import android.content.res.Configuration; 27 import android.content.res.Resources; 28 import android.graphics.drawable.Drawable; 29 import android.os.Bundle; 30 import android.text.TextUtils; 31 import android.util.Log; 32 import android.view.LayoutInflater; 33 import android.view.Menu; 34 import android.view.MenuInflater; 35 import android.view.MenuItem; 36 import android.view.View; 37 import android.view.ViewGroup; 38 import android.widget.ArrayAdapter; 39 import android.widget.ImageView; 40 import android.widget.ListView; 41 import android.widget.SearchView; 42 import android.widget.TextView; 43 44 import androidx.annotation.NonNull; 45 import androidx.core.content.ContextCompat; 46 import androidx.fragment.app.FragmentActivity; 47 import androidx.fragment.app.FragmentManager; 48 import androidx.fragment.app.ListFragment; 49 import androidx.loader.app.LoaderManager; 50 import androidx.loader.content.AsyncTaskLoader; 51 import androidx.loader.content.Loader; 52 53 import com.example.android.supportv4.R; 54 55 import java.io.File; 56 import java.text.Collator; 57 import java.util.ArrayList; 58 import java.util.Collections; 59 import java.util.Comparator; 60 import java.util.List; 61 62 /** 63 * Demonstration of the implementation of a custom Loader. 64 */ 65 public class LoaderCustomSupport extends FragmentActivity { 66 67 @Override onCreate(Bundle savedInstanceState)68 protected void onCreate(Bundle savedInstanceState) { 69 super.onCreate(savedInstanceState); 70 71 FragmentManager fm = getSupportFragmentManager(); 72 73 // Create the list fragment and add it as our sole content. 74 if (fm.findFragmentById(android.R.id.content) == null) { 75 AppListFragment list = new AppListFragment(); 76 fm.beginTransaction().add(android.R.id.content, list).commit(); 77 } 78 } 79 80 //BEGIN_INCLUDE(loader) 81 /** 82 * This class holds the per-item data in our Loader. 83 */ 84 public static class AppEntry { AppEntry(AppListLoader loader, ApplicationInfo info)85 public AppEntry(AppListLoader loader, ApplicationInfo info) { 86 mLoader = loader; 87 mInfo = info; 88 mApkFile = new File(info.sourceDir); 89 } 90 getApplicationInfo()91 public ApplicationInfo getApplicationInfo() { 92 return mInfo; 93 } 94 getLabel()95 public String getLabel() { 96 return mLabel; 97 } 98 getIcon()99 public Drawable getIcon() { 100 if (mIcon == null) { 101 if (mApkFile.exists()) { 102 mIcon = mInfo.loadIcon(mLoader.mPm); 103 return mIcon; 104 } else { 105 mMounted = false; 106 } 107 } else if (!mMounted) { 108 // If the app wasn't mounted but is now mounted, reload 109 // its icon. 110 if (mApkFile.exists()) { 111 mMounted = true; 112 mIcon = mInfo.loadIcon(mLoader.mPm); 113 return mIcon; 114 } 115 } else { 116 return mIcon; 117 } 118 119 return ContextCompat.getDrawable( 120 mLoader.getContext(), android.R.drawable.sym_def_app_icon); 121 } 122 toString()123 @Override public String toString() { 124 return mLabel; 125 } 126 loadLabel(Context context)127 void loadLabel(Context context) { 128 if (mLabel == null || !mMounted) { 129 if (!mApkFile.exists()) { 130 mMounted = false; 131 mLabel = mInfo.packageName; 132 } else { 133 mMounted = true; 134 CharSequence label = mInfo.loadLabel(context.getPackageManager()); 135 mLabel = label != null ? label.toString() : mInfo.packageName; 136 } 137 } 138 } 139 140 private final AppListLoader mLoader; 141 private final ApplicationInfo mInfo; 142 private final File mApkFile; 143 private String mLabel; 144 private Drawable mIcon; 145 private boolean mMounted; 146 } 147 148 /** 149 * Perform alphabetical comparison of application entry objects. 150 */ 151 public static final Comparator<AppEntry> ALPHA_COMPARATOR = new Comparator<AppEntry>() { 152 private final Collator sCollator = Collator.getInstance(); 153 @Override 154 public int compare(AppEntry object1, AppEntry object2) { 155 return sCollator.compare(object1.getLabel(), object2.getLabel()); 156 } 157 }; 158 159 /** 160 * Helper for determining if the configuration has changed in an interesting 161 * way so we need to rebuild the app list. 162 */ 163 public static class InterestingConfigChanges { 164 final Configuration mLastConfiguration = new Configuration(); 165 int mLastDensity; 166 applyNewConfig(Resources res)167 boolean applyNewConfig(Resources res) { 168 int configChanges = mLastConfiguration.updateFrom(res.getConfiguration()); 169 boolean densityChanged = mLastDensity != res.getDisplayMetrics().densityDpi; 170 if (densityChanged || (configChanges & (ActivityInfo.CONFIG_LOCALE 171 | ActivityInfo.CONFIG_UI_MODE | ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0) { 172 mLastDensity = res.getDisplayMetrics().densityDpi; 173 return true; 174 } 175 return false; 176 } 177 } 178 179 /** 180 * Helper class to look for interesting changes to the installed apps 181 * so that the loader can be updated. 182 */ 183 public static class PackageIntentReceiver extends BroadcastReceiver { 184 final AppListLoader mLoader; 185 PackageIntentReceiver(AppListLoader loader)186 public PackageIntentReceiver(AppListLoader loader) { 187 mLoader = loader; 188 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); 189 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 190 filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 191 filter.addDataScheme("package"); 192 mLoader.getContext().registerReceiver(this, filter); 193 // Register for events related to sdcard installation. 194 IntentFilter sdFilter = new IntentFilter(); 195 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE); 196 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 197 mLoader.getContext().registerReceiver(this, sdFilter); 198 } 199 onReceive(Context context, Intent intent)200 @Override public void onReceive(Context context, Intent intent) { 201 // Tell the loader about the change. 202 mLoader.onContentChanged(); 203 } 204 } 205 206 /** 207 * A custom Loader that loads all of the installed applications. 208 */ 209 public static class AppListLoader extends AsyncTaskLoader<List<AppEntry>> { 210 final InterestingConfigChanges mLastConfig = new InterestingConfigChanges(); 211 final PackageManager mPm; 212 213 List<AppEntry> mApps; 214 PackageIntentReceiver mPackageObserver; 215 AppListLoader(Context context)216 public AppListLoader(Context context) { 217 super(context); 218 219 // Retrieve the package manager for later use; note we don't 220 // use 'context' directly but instead the save global application 221 // context returned by getContext(). 222 mPm = getContext().getPackageManager(); 223 } 224 225 /** 226 * This is where the bulk of our work is done. This function is 227 * called in a background thread and should generate a new set of 228 * data to be published by the loader. 229 */ loadInBackground()230 @Override public List<AppEntry> loadInBackground() { 231 // Retrieve all known applications. 232 //noinspection WrongConstant 233 List<ApplicationInfo> apps = mPm.getInstalledApplications( 234 PackageManager.MATCH_UNINSTALLED_PACKAGES 235 | PackageManager.MATCH_DISABLED_COMPONENTS); 236 if (apps == null) { 237 apps = new ArrayList<ApplicationInfo>(); 238 } 239 240 final Context context = getContext(); 241 242 // Create corresponding array of entries and load their labels. 243 List<AppEntry> entries = new ArrayList<AppEntry>(apps.size()); 244 for (int i = 0; i < apps.size(); i++) { 245 AppEntry entry = new AppEntry(this, apps.get(i)); 246 entry.loadLabel(context); 247 entries.add(entry); 248 } 249 250 // Sort the list. 251 Collections.sort(entries, ALPHA_COMPARATOR); 252 253 // Done! 254 return entries; 255 } 256 257 /** 258 * Called when there is new data to deliver to the client. The 259 * super class will take care of delivering it; the implementation 260 * here just adds a little more logic. 261 */ deliverResult(List<AppEntry> apps)262 @Override public void deliverResult(List<AppEntry> apps) { 263 if (isReset()) { 264 // An async query came in while the loader is stopped. We 265 // don't need the result. 266 if (apps != null) { 267 onReleaseResources(apps); 268 } 269 } 270 List<AppEntry> oldApps = apps; 271 mApps = apps; 272 273 if (isStarted()) { 274 // If the Loader is currently started, we can immediately 275 // deliver its results. 276 super.deliverResult(apps); 277 } 278 279 // At this point we can release the resources associated with 280 // 'oldApps' if needed; now that the new result is delivered we 281 // know that it is no longer in use. 282 if (oldApps != null) { 283 onReleaseResources(oldApps); 284 } 285 } 286 287 /** 288 * Handles a request to start the Loader. 289 */ onStartLoading()290 @Override protected void onStartLoading() { 291 if (mApps != null) { 292 // If we currently have a result available, deliver it 293 // immediately. 294 deliverResult(mApps); 295 } 296 297 // Start watching for changes in the app data. 298 if (mPackageObserver == null) { 299 mPackageObserver = new PackageIntentReceiver(this); 300 } 301 302 // Has something interesting in the configuration changed since we 303 // last built the app list? 304 boolean configChange = mLastConfig.applyNewConfig(getContext().getResources()); 305 306 if (takeContentChanged() || mApps == null || configChange) { 307 // If the data has changed since the last time it was loaded 308 // or is not currently available, start a load. 309 forceLoad(); 310 } 311 } 312 313 /** 314 * Handles a request to stop the Loader. 315 */ onStopLoading()316 @Override protected void onStopLoading() { 317 // Attempt to cancel the current load task if possible. 318 cancelLoad(); 319 } 320 321 /** 322 * Handles a request to cancel a load. 323 */ onCanceled(List<AppEntry> apps)324 @Override public void onCanceled(List<AppEntry> apps) { 325 super.onCanceled(apps); 326 327 // At this point we can release the resources associated with 'apps' 328 // if needed. 329 onReleaseResources(apps); 330 } 331 332 /** 333 * Handles a request to completely reset the Loader. 334 */ onReset()335 @Override protected void onReset() { 336 super.onReset(); 337 338 // Ensure the loader is stopped 339 onStopLoading(); 340 341 // At this point we can release the resources associated with 'apps' 342 // if needed. 343 if (mApps != null) { 344 onReleaseResources(mApps); 345 mApps = null; 346 } 347 348 // Stop monitoring for changes. 349 if (mPackageObserver != null) { 350 getContext().unregisterReceiver(mPackageObserver); 351 mPackageObserver = null; 352 } 353 } 354 355 /** 356 * Helper function to take care of releasing resources associated 357 * with an actively loaded data set. 358 */ onReleaseResources(List<AppEntry> apps)359 protected void onReleaseResources(List<AppEntry> apps) { 360 // For a simple List<> there is nothing to do. For something 361 // like a Cursor, we would close it here. 362 } 363 } 364 //END_INCLUDE(loader) 365 366 //BEGIN_INCLUDE(fragment) 367 public static class AppListAdapter extends ArrayAdapter<AppEntry> { 368 private final LayoutInflater mInflater; 369 AppListAdapter(Context context)370 public AppListAdapter(Context context) { 371 super(context, android.R.layout.simple_list_item_2); 372 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 373 } 374 setData(List<AppEntry> data)375 public void setData(List<AppEntry> data) { 376 clear(); 377 if (data != null) { 378 for (AppEntry appEntry : data) { 379 add(appEntry); 380 } 381 } 382 } 383 384 /** 385 * Populate new items in the list. 386 */ getView(int position, View convertView, ViewGroup parent)387 @Override public View getView(int position, View convertView, ViewGroup parent) { 388 View view; 389 390 if (convertView == null) { 391 view = mInflater.inflate(R.layout.list_item_icon_text, parent, false); 392 } else { 393 view = convertView; 394 } 395 396 AppEntry item = getItem(position); 397 ((ImageView)view.findViewById(R.id.icon)).setImageDrawable(item.getIcon()); 398 ((TextView)view.findViewById(R.id.text)).setText(item.getLabel()); 399 400 return view; 401 } 402 } 403 404 public static class AppListFragment extends ListFragment 405 implements LoaderManager.LoaderCallbacks<List<AppEntry>> { 406 407 // This is the Adapter being used to display the list's data. 408 AppListAdapter mAdapter; 409 410 // If non-null, this is the current filter the user has provided. 411 String mCurFilter; 412 onActivityCreated(Bundle savedInstanceState)413 @Override public void onActivityCreated(Bundle savedInstanceState) { 414 super.onActivityCreated(savedInstanceState); 415 416 // Give some text to display if there is no data. In a real 417 // application this would come from a resource. 418 setEmptyText("No applications"); 419 420 // We have a menu item to show in action bar. 421 setHasOptionsMenu(true); 422 423 // Create an empty adapter we will use to display the loaded data. 424 mAdapter = new AppListAdapter(getActivity()); 425 setListAdapter(mAdapter); 426 427 // Start out with a progress indicator. 428 setListShown(false); 429 430 // Prepare the loader. Either re-connect with an existing one, 431 // or start a new one. 432 getLoaderManager().initLoader(0, null, this); 433 } 434 onCreateOptionsMenu(Menu menu, MenuInflater inflater)435 @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 436 // Place an action bar item for searching. 437 MenuItem item = menu.add("Search"); 438 item.setIcon(android.R.drawable.ic_menu_search); 439 item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM 440 | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); 441 final SearchView searchView = new SearchView(getActivity()); 442 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 443 @Override 444 public boolean onQueryTextChange(String newText) { 445 // Called when the action bar search text has changed. Since this 446 // is a simple array adapter, we can just have it do the filtering. 447 mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; 448 mAdapter.getFilter().filter(mCurFilter); 449 return true; 450 } 451 452 @Override 453 public boolean onQueryTextSubmit(String query) { 454 return false; 455 } 456 }); 457 458 searchView.setOnCloseListener(new SearchView.OnCloseListener() { 459 @Override 460 public boolean onClose() { 461 if (!TextUtils.isEmpty(searchView.getQuery())) { 462 searchView.setQuery(null, true); 463 } 464 return true; 465 } 466 }); 467 468 item.setActionView(searchView); 469 } 470 onListItemClick(ListView l, View v, int position, long id)471 @Override public void onListItemClick(ListView l, View v, int position, long id) { 472 // Insert desired behavior here. 473 Log.i("LoaderCustom", "Item clicked: " + id); 474 } 475 476 @NonNull onCreateLoader(int id, Bundle args)477 @Override public Loader<List<AppEntry>> onCreateLoader(int id, Bundle args) { 478 // This is called when a new Loader needs to be created. This 479 // sample only has one Loader with no arguments, so it is simple. 480 return new AppListLoader(getActivity()); 481 } 482 onLoadFinished(@onNull Loader<List<AppEntry>> loader, List<AppEntry> data)483 @Override public void onLoadFinished(@NonNull Loader<List<AppEntry>> loader, 484 List<AppEntry> data) { 485 // Set the new data in the adapter. 486 mAdapter.setData(data); 487 488 // The list should now be shown. 489 if (isResumed()) { 490 setListShown(true); 491 } else { 492 setListShownNoAnimation(true); 493 } 494 } 495 onLoaderReset(@onNull Loader<List<AppEntry>> loader)496 @Override public void onLoaderReset(@NonNull Loader<List<AppEntry>> loader) { 497 // Clear the data in the adapter. 498 mAdapter.setData(null); 499 } 500 } 501 //END_INCLUDE(fragment) 502 } 503