Android storage manager example

Как использовать Android Storage Manager

Управляйте своими файлами и освобождайте место, погрузившись в настройки

Пользователи Android могут быстро очистить память телефона с помощью диспетчера хранилища, расположенного в приложении настроек.

До Android Marshmallow вам приходилось использовать сторонние приложения для управления файлами, но как только вы обновили ОС до версии 5.0 Lollipop, вам больше не нужно ничего скачивать. Очистка пространства на вашем телефоне является важной частью его обслуживания, особенно если у вас нет тонны внутренней памяти или слота для карт памяти.

Вы получаете место для новых приложений, фотографий, видео и музыки, а зачастую и для более быстрой работы; когда ваш телефон почти заполнен, он становится вялым. Android называет эту функцию хранилищем, но управление файлами – это то, что она делает.

Приведенные ниже инструкции должны применяться независимо от того, кто сделал ваш телефон Android: Samsung, Google, Huawei, Xiaomi и т. Д.

Вот все, что вам нужно знать об управлении файлами и хранилищем на Android.

Как освободить место с помощью диспетчера хранилища

Чтобы получить доступ к файлам, перейдите в Настройки и выберите Хранилище . Прежде чем нажать Хранилище , вы сразу увидите, сколько свободного места доступно: X% использовано – X ГБ свободно . Та же самая информация находится вверху страницы хранилища.

Нажмите кнопку Свободное место под этой информацией, и вы увидите, что ваши файлы упорядочены по категориям: резервные копии фотографий и видео , загрузки , и Редко используемые приложения , а также количество гигабайт в каждом.

Опция Резервное копирование фотографий и видео – это все или ничего; Вы не можете выбрать конкретные файлы.

Нажмите Загрузки , чтобы просмотреть список файлов PDF и других документов.

Нажмите Редко используемые приложения , и вы увидите список приложений, упорядоченных по тому, как недавно вы их использовали, и приложения, которые вы проигнорировали, самые длинные вверху.

Затем вы можете включить Smart Storage , который автоматически удаляет старые фотографии и видео, когда на вашем телефоне заканчивается свободное место.

Наконец, есть список всего, что есть на вашем телефоне, в категориях, включая музыку и аудио, игры, файлы и системы (файлы должны работать в вашей ОС). Нажмите на категорию, чтобы просмотреть связанные с ней приложения, нажмите на приложение, и вы сможете очистить кэш или очистить данные (файлы, настройки, учетные записи и т. Д.). Эти действия часто могут устранить проблемы с приложением, которое работает.

Чтобы удалить нежелательное приложение или приложение, которое не работает должным образом, вы можете посетить Google Play Store, нажать Мои приложения, выбрать приложение и нажать Удалить .

Другой способ – перетащить ненужные приложения из ящика приложений в значок корзины, который появляется при нажатии и удерживании приложения. К сожалению, вы не можете удалить многие предварительно загруженные приложения, иначе известные как вирусы, без рутирования вашего устройства.

Тем не менее, сначала рекомендуется создать резервную копию данных, если вы случайно удалили что-то важное.

Еще один способ освободить место на вашем смартфоне Android – создать резервную копию ваших фотографий в Google Photos, которая предлагает неограниченное облачное хранилище и позволяет получать доступ к изображениям на любом устройстве. Для других файлов вы можете перенести их в Dropbox, Google Drive или в свою облачную службу.

Как это складывается

Файловый менеджер Android минималистичен и не может конкурировать со сторонними приложениями, такими как ES File Explorer (от ES Global) или Asus File Manager (от ZenUI, Asus Computer Inc.). ES File Explorer имеет множество функций, включая передачу по Bluetooth и Wi-Fi, совместимость с популярными облачными сервисами хранения, удаленный файловый менеджер, который позволяет получать доступ к файлам телефона на вашем компьютере, очиститель кэша и многое другое.

Asus File Manager обладает многими из этих функций, включая интеграцию облачного хранилища, инструменты сжатия файлов, анализатор хранилища и возможность доступа к файлам LAN и SMB.

Читайте также:  Чем проверить память андроида

Конечно, если вы хотите получить доступ к системным файлам, вам нужно будет рутировать свой смартфон и установить сторонний файловый менеджер. Руттинг вашего смартфона – простой процесс, и риски относительно невелики. Преимущества включают возможность управлять всеми файлами на вашем смартфоне, удалять вредоносные программы и многое другое. ES File Explorer имеет инструмент Root Explorer, который позволяет пользователям контролировать всю файловую систему, каталоги данных и разрешения.

Тем не менее, если вы просто хотите выполнить быструю очистку, как на компьютере, встроенный инструмент поможет.

Источник

How to Use Android’s Storage Manager

Manage your files and free up space by dipping into your settings

What to Know

  • Go to Settings >Storage. Toggle on Smart Storage to automatically delete old photos and videos when the phone is low on space.
  • Tap an app and clear its cache or data (files, settings, and accounts) to address problems with an app that acts up.
  • Tap Free Up Space to display files organized by category. Select any items you want to remove and tap Free up X GB.

This article explains how to clear up phone storage on your Android device using the built-in storage manager in Settings. This information applies to Android devices made by Samsung, Google, Huawei, Xiaomi, and more.

How to Free up Space With the Storage Manager

When you free up space on your Android device, the phone has more space for new apps, photos, videos, and music, and often, faster performance. When a phone is close to full, it tends to get sluggish. Android refers to this feature as storage, but file management is what it does.

To access your files, go to Settings. The Storage section displays how much room is available: X% used — X GB free.

Tap Storage.

You’ll see a list of everything on your phone, in categories including music & audio, games, files, and system (files need to run your OS). You can toggle on Smart Storage at the top, which automatically deletes old photos and videos when the phone is close to running out of space.

Tap a category to view the apps associated with it.

Tap an app, and clear the cache or clear data (files, settings, and accounts). These actions can often fix problems with an app that’s acting up.

Go back to Storage settings.

Tap Free Up Space to display files organized by category: Backed up photos & videos, Downloads, and Infrequently used apps, along with how many gigabytes each uses.

The Backed up photos & videos option is all or nothing; you can’t select specific files.

Tap Downloads to see a list of PDFs and other documents.

Under Infrequently used apps is a list of apps organized by how recently you’ve opened them.

Select any items you’d like to remove and tap Free up X GB. You’ll get a confirmation popup message that offers to turn on Smart Storage if it’s not already enabled.

To delete an unwanted app, go to the Google Play Store, tap My Apps, select the app, and tap Uninstall.

Another method is to drag unwanted apps from the app drawer to the trash icon that appears when you press and hold an app.

You can’t delete many pre-loaded apps, otherwise known as bloatware, without rooting the device.

Alternative Ways to Free up Space on Your Android

Another way to make space on an Android smartphone is to back up your pictures to Google Photos, which offers unlimited cloud storage and access to your images on any device. For other files, offload them to Dropbox, Google Drive, or another cloud service. You can also move apps to an SD card to save space.

If you want to access Android system files, you can root your smartphone and install a third-party file manager. Rooting your smartphone is a straightforward process, and the risks are relatively small. The benefits include the ability to manage files on the smartphone, remove bloatware, and more.

If you want to do a quick cleanup, as you would on a computer, the built-in tool does the trick.

Always be sure to back up your data first, in case you accidentally delete something important.

Читайте также:  Как использовать все возможности android

Источник

Android External Storage with Examples

In android, we have different storage options such as shared preferences, internal storage, external storage, SQLite storage, etc. to store and retrieve the application data based on our requirements.

In previous chapters, we learned how to use Shared Preferences, Internal Storage and now we will see how to use the External Storage option to store and retrieve the data from external storage media such as SD card.

In android, External Storage is useful to store the data files publically on the shared external storage using the FileOutputStream object. After storing the data files on external storage, we can read the data file from external storage media using a FileInputStream object.

The data files saved in external storage are word-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

Grant Access to External Storage

To read or write files on the external storage, our app must acquire the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system permissions. For that, we need to add the following permissions in the android manifest file like as shown below.

manifest >
.
uses-permission android :name= «android.permission.WRITE_EXTERNAL_STORAGE»/>
uses-permission android :name= «android.permission.READ_EXTERNAL_STORAGE»/>
.
manifest >

Checking External Storage Availability

Before we do any work with external storage, first we need to check whether the media is available or not by calling getExternalStorageState(). The media might be mounted to a computer, missing, read-only or in some other state. To get the media status, we need to write the code like as shown below.

boolean Available= false ;
boolean Readable= false ;
String state = Environment.getExternalStorageState();
if (Environment. MEDIA_MOUNTED .equals(state)) <
// Both Read and write operations available
Available= true ;
> else if (Environment. MEDIA_MOUNTED_READ_ONLY .equals(state)) <
// Only Read operation available
Available= true ;
Readable= true ;
> else <
// SD card not mounted
Available = false ;
>

If you observe the above code snippet, we used getExternalStorageState() method to know the status of media mounted to a computer, such as missing, read-only or in some other state.

In android, by using getExternalStoragePublishDirectory() method we can access the files from appropriate public directory by passing the type of directory we want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, etc. based on our requirements.

If we save our files to corresponding media-type public directory, the system’s media scanner can properly categorize our files in the system.

Following is the example to create a directory for a new photo album in the public pictures directory.

In case, if we are handling the files that are not intended for other apps to use, then we should use a private storage directory on the external storage by calling getExternalFilesDir().

Write a File to External Storage

By using android FileOutputStream object and getExternalStoragePublicDirectory method, we can easily create and write data to the file in external storage public folders.

Following is the code snippet to create and write a public file in the device Downloads folder.

String FILENAME = «user_details» ;
String name = «suresh» ;

File folder = Environment.getExternalStoragePublicDirectory(Environment. DIRECTORY_DOWNLOADS );
File myFile = new File(folder, FILENAME);
FileOutputStream fstream = new FileOutputStream(myFile);

If you observe above code, we are creating and writing a file in device public Downloads folder by using getExternalStoragePublicDirectory method. We used write() method to write the data in file and used close() method to close the stream.

Read a File from External Storage

By using the android FileInputStream object and getExternalStoragePublicDirectory method, we can easily read the file from external storage.

Following is the code snippet to read data from a file that is in the downloads folder.

String FILENAME = «user_details» ;
File folder = Environment.getExternalStoragePublicDirectory(Environment. DIRECTORY_DOWNLOADS );
File myFile = new File(folder, FILENAME );
FileInputStream fstream = new FileInputStream(myFile);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream .read())!= — 1 ) <
sbuffer.append(( char )i);
>
fstream .close();

If you observe above code, we are reading a file from device Downloads folder storage by using FileInputStream object getExternalStoragePublicDirectory method with file name. We used read() method to read one character at a time from the file and used close() method to close the stream.

Now we will see how to save or write file to external memory and read the file data from external storage using android FileInputStream and FileOutputStream objects in android applications with examples.

Читайте также:  Название смартфонов с андроида

Android External Storage Example

Following is the example of storing and retrieving the data files from external memory by using FileOutputStream and FileInputStream objects.

Create a new android application using android studio and give names as ExternalStorageExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

Now we will create another layout resource file details.xml in \res\layout path to get the first activity (activity_main.xml) details in second activity file for that right click on your layout folder à Go to New à select Layout Resource File and give name as details.xml.

Once we create a new layout resource file details.xml, open it and write the code like as shown below

details.xml

Now open your main activity file MainActivity.java from \java\com.tutlane.externalstorageexample path and write the code like as shown below

MainActivity.java

package com.tutlane.externalstorageexample;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity <
EditText uname , pwd ;
Button saveBtn ;
FileOutputStream fstream ;
Intent intent ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
uname = (EditText)findViewById(R.id. txtName );
pwd = (EditText)findViewById(R.id. txtPwd );
saveBtn = (Button)findViewById(R.id. btnSave );
saveBtn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
String username = uname .getText().toString()+ » \n » ;
String password = pwd .getText().toString();
try <
ActivityCompat.requestPermissions(MainActivity. this , new String[], 23 );
File folder = Environment.getExternalStoragePublicDirectory(Environment. DIRECTORY_DOWNLOADS );
File myFile = new File(folder, «user_details» );
fstream = new FileOutputStream(myFile);
fstream .write(username.getBytes());
fstream .write(password.getBytes());
fstream .close();
Toast.makeText(getApplicationContext(), «Details Saved in » +myFile.getAbsolutePath(),Toast. LENGTH_SHORT ).show();
intent = new Intent(MainActivity. this ,DetailsActivity. class );
startActivity( intent );
> catch (FileNotFoundException e) <
e.printStackTrace();
> catch (IOException e) <
e.printStackTrace();
>
>
>);
>
>

If you observe above code, we are taking entered username and password details and saving it in device external memory and redirecting the user to another activity.

Now we will create another activity file DetailsActivity.java in \java\com.tutlane.externalstorageexample path to show the details from external storage for that right-click on your application folder à Go to New à select Java Class and give name as DetailsActivity.java.

Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below

DetailsActivity.java

package com.tutlane.externalstorageexample;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* Created by tutlane on 05-01-2018.
*/

public class DetailsActivity extends AppCompatActivity <
FileInputStream fstream ;
Intent intent ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. details );
TextView result = (TextView)findViewById(R.id. resultView );
Button back = (Button)findViewById(R.id. btnBack );
try <
File folder = Environment.getExternalStoragePublicDirectory(Environment. DIRECTORY_DOWNLOADS );
File myFile = new File(folder, «user_details» );
fstream = new FileInputStream(myFile);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream .read())!= — 1 ) <
sbuffer.append(( char )i);
>
fstream .close();
String details[] = sbuffer.toString().split( » \n » );
result.setText( «Name: » + details[ 0 ]+ » \n Password: » +details[ 1 ]);
> catch (FileNotFoundException e) <
e.printStackTrace();
> catch (IOException e) <
e.printStackTrace();
>
back.setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
intent = new Intent(DetailsActivity. this ,MainActivity. class );
startActivity( intent );
>
>);
>
>

Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.

AndroidManifest.xml

If you observe above example, we are saving entered details file and redirecting the user to another activity file (DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.

Output of Android External Storage Example

When we run above example in the android emulator we will get a result like as shown below

If you observe the above result, the entered username and password details are storing in external memory and redirecting the user to another activity file to show the user details from external storage file. After that, if we click on the Back button, it will redirect the user to the login page.

This is how we can use the External Storage option in android applications to store and retrieve data from device external memory based on our requirements.

Источник

Оцените статью