首页>Program>source

我有一个带有单击按钮的活动,它将打开一个带有3个具有标签布局的片段的新活动,第一个片段从recyclerview中的内部存储加载文件,第二个片段在recyclerview中加载已安装的应用程序,第三个片段在联系人中加载联系人. recyclerview,但是我面临的问题是,当我单击该按钮以启动活动时,它需要2-3秒才能启动该活动,并且我在包含很多应用程序的设备上进行了测试,并使其崩溃,并且 没有打开活动,我认为这是因为一次加载所有数据需要时间,如何解决此问题?

这是片段中的代码

FileListFragment.java


public class FileListFragment extends Fragment implements FilesStateManager {
    private static final String TAG = "FileListFragment";
    RecyclerView fileListRecyclerView,currentPathRecyclerView;
    TextView currentPathTextView;
    ArrayList<FileObject> fileObjects = new ArrayList<>();
    ArrayList<FileObject> currentFolders = new ArrayList<>();
    static ArrayList<FileObject> selectedFiles = new ArrayList<>();
    String currentPath = "";
    String initialPath = "";
    String pathToShow = "/";
    RelativeLayout grantPermissionContainer;
    Button grantPermissionButton;
    FileManager fileManager;
    static DataSelectedManager dataSelectedManager;
    public FileListFragment(DataSelectedManager dataSelectedManager) {
        this.dataSelectedManager = dataSelectedManager;
    }
    private final int PERMISSION_CODE = 100;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_file_list,container,false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        currentPathRecyclerView = view.findViewById(R.id.current_folder_recyclerview);
        fileListRecyclerView = view.findViewById(R.id.folder_list_recyclerview);
        grantPermissionContainer = view.findViewById(R.id.grant_permission_container);
        grantPermissionButton = view.findViewById(R.id.grant_permission_button);
        init();
    }
    private void init(){
        fileManager = new FileManager(getContext());
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            grantPermissionContainer.setVisibility(View.VISIBLE);
            fileListRecyclerView.setVisibility(View.GONE);
        }
        grantPermissionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT < 16) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
                }
            }
        });
        try{
            String path = getActivity().getExternalFilesDir(null).getPath();
            currentPath = path.split("Android")[0];
            initialPath = currentPath;
            FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
            currentFolders.add(fileObject);
            setupCurrentPathRecyclerView();
            readFiles();
            Log.d(TAG, "init: " + path);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: Called");
        if (requestCode == PERMISSION_CODE){
            Log.d(TAG, "onRequestPermissionsResult: Codes matched");
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
                grantPermissionContainer.setVisibility(View.GONE);
                fileListRecyclerView.setVisibility(View.VISIBLE);
                FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
                currentFolders.add(fileObject);
                setupCurrentPathRecyclerView();
                readFiles();
            }
        }
    }
    private void readFiles(){
        fileObjects = fileManager.readFiles(currentPath,selectedFiles);
        setupRecyclerView();
    }
    private void setupRecyclerView(){
        FileListAdapter fileListAdapter = new FileListAdapter(fileObjects,selectedFiles,getContext(),this);
        fileListRecyclerView.setAdapter(fileListAdapter);
        fileListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }
    private void setupCurrentPathRecyclerView(){
        FolderPathAdapter folderPathAdapter = new FolderPathAdapter(currentFolders,getContext(),this);
        currentPathRecyclerView.setAdapter(folderPathAdapter);
        currentPathRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false));
        currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
    }
    @Override
    public void folderClicked(FileObject fileObject) {
        currentPath = fileObject.getPath();
        currentFolders.add(fileObject);
        currentPathRecyclerView.getAdapter().notifyItemInserted(currentFolders.size() - 1);
        currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
        readFiles();
    }
    @Override
    public void pathFolderClicked(FileObject fileObject) {
        Log.d(TAG, "pathFolderClicked: Called");
        if (!fileObject.getPath().equals(currentFolders.get(currentFolders.size() - 1).getPath())){
            for (FileObject folder : currentFolders){
                if (folder.getPath().equals(fileObject.getPath())){
                    int index = currentFolders.indexOf(folder) + 1;
                    int size = currentFolders.size();
                    currentFolders = new ArrayList<>(currentFolders.subList(0,index));
                    Log.d(TAG, "pathFolderClicked: Number of item " + (size - index) + " Index: " + index);
//                    currentPathRecyclerView.getAdapter().notifyItemRangeRemoved(index,size - index);
                    setupCurrentPathRecyclerView();
                    currentPath = currentFolders.get(currentFolders.size() - 1).getPath();
                    readFiles();
                    Log.d(TAG, "pathFolderClicked: Notified");
                }
            }
            Log.d(TAG, "pathFolderClicked: " + Arrays.toString(currentFolders.toArray()));
        }
    }
    @Override
    public void fileSelected(FileObject fileObject) {
        selectedFiles.add(fileObject);
        dataSelectedManager.dataSelected();
    }
    @Override
    public void fileDeselected(FileObject fileObject) {
        ArrayList<FileObject> filesToRemove = new ArrayList<>();
        for (FileObject fileObject1 : selectedFiles){
            if (fileObject.getPath().equals(fileObject1.getPath())){
                filesToRemove.add(fileObject1);
            }
        }
        dataSelectedManager.dataDeSelected();
        selectedFiles.removeAll(filesToRemove);
    }
    public static void triggerDataTransfer(){
        dataSelectedManager.sendSelectedFiles(selectedFiles);
    }
}

AppListFragment.java

public class AppListFragment extends Fragment implements AppsStateManager {
    RecyclerView appListRecyclerView;
    TextView selectAllTextView;
    CheckBox selectAllCheckBox;
    static ArrayList<App> apps = new ArrayList<>();
    AppsManager appsManager;
    static DataSelectedManager dataSelectedManager;
    public AppListFragment(DataSelectedManager dataSelectedManager) {
        this.dataSelectedManager = dataSelectedManager;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_app_list,container,false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        appListRecyclerView = view.findViewById(R.id.app_recycler_view);
        selectAllTextView = view.findViewById(R.id.select_all_text_view);
        selectAllCheckBox = view.findViewById(R.id.select_all_checkbox);
        appsManager = new AppsManager(getActivity().getPackageManager(),getActivity().getApplicationContext().getPackageName());
        getInstalledApps();
        setupRecyclerView();
        selectAllCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!selectAllCheckBox.isChecked()){
                    for (App app : apps){
                        if (app.isSelected()){
                            app.setSelected(false);
                            dataSelectedManager.dataDeSelected();
                        }
                    }
                }
                else {
                    for (App app : apps){
                        if (!app.isSelected()){
                            app.setSelected(true);
                            dataSelectedManager.dataSelected();
                        }
                    }
                }
                appListRecyclerView.getAdapter().notifyDataSetChanged();
            }
        });
    }
    private void getInstalledApps(){
        apps = appsManager.getInstalledApps();
        selectAllTextView.setText("Select All (" + apps.size() + ")");
    }

    private void setupRecyclerView(){
        AppListAdapter appListAdapter = new AppListAdapter(apps,getContext(),this);
        appListRecyclerView.setAdapter(appListAdapter);
        appListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }
    @Override
    public void deSelected() {
        selectAllCheckBox.setChecked(false);
        dataSelectedManager.dataDeSelected();
    }
    @Override
    public void selected() {
        dataSelectedManager.dataSelected();
    }
    public static void triggerDataTransfer(){
        ArrayList<App> selectedApps = new ArrayList<>();
        for (App app : apps){
            if (app.isSelected()){
                selectedApps.add(app);
            }
        }
        dataSelectedManager.sendSelectedApps(selectedApps);
    }
}

ContactListFragment.java

public class ContactListFragment extends Fragment implements ContactsStateManager {
    private static final String TAG = "ContactListFragment";
    static ArrayList<Contact> contacts = new ArrayList<>();
    TextView selectAllTextView;
    CheckBox selectAllRadioButton;
    Button grantPermissionButton;
    RelativeLayout grantPermissionLayout;
    RecyclerView contactsRecyclerView;
    ContactsManager contactsManager;
    static DataSelectedManager dataSelectedManager;
    public ContactListFragment(DataSelectedManager dataSelectedManager) {
        this.dataSelectedManager = dataSelectedManager;
    }
    private final int PERMISSION_CODE = 101;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_contact_list,container,false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        contactsRecyclerView = view.findViewById(R.id.contacts_recycler_view);
        selectAllTextView = view.findViewById(R.id.select_all_text_view);
        selectAllRadioButton = view.findViewById(R.id.select_all_checkbox);
        grantPermissionLayout = view.findViewById(R.id.grant_permission_container);
        grantPermissionButton = view.findViewById(R.id.grant_permission_button);
        contactsManager = new ContactsManager(getActivity().getContentResolver());
        selectAllRadioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            if (!selectAllRadioButton.isChecked()){
                for (Contact contact: contacts){
                    if (contact.isSelected()){
                        contact.setSelected(false);
                        dataSelectedManager.dataDeSelected();
                    }
                }
            }
            else{
                for (Contact contact: contacts){
                    if (!contact.isSelected()){
                        contact.setSelected(true);
                        dataSelectedManager.dataSelected();
                    }
                }
            }
               contactsRecyclerView.getAdapter().notifyDataSetChanged();
            }
        });
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            grantPermissionLayout.setVisibility(View.VISIBLE);
            contactsRecyclerView.setVisibility(View.GONE);
        }
        else{
            readContacts();
            setupRecyclerView();
        }
        grantPermissionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},PERMISSION_CODE);
            }
        });
    }
    private void readContacts(){
        contacts = contactsManager.getContacts();
        selectAllTextView.setText("Select All (" + contacts.size() + ")");
    }
    private void setupRecyclerView(){
        ContactListAdapter contactListAdapter = new ContactListAdapter(contacts,getContext(),this);
        contactsRecyclerView.setAdapter(contactListAdapter);
        contactsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: Called");
        if (requestCode == PERMISSION_CODE){
            Log.d(TAG, "onRequestPermissionsResult: Codes matched");
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
                grantPermissionLayout.setVisibility(View.GONE);
                readContacts();
                contactsRecyclerView.setVisibility(View.VISIBLE);
                setupRecyclerView();
            }
        }
    }
    @Override
    public void deSelected() {
        selectAllRadioButton.setChecked(false);
        dataSelectedManager.dataDeSelected();
    }
    @Override
    public void selected() {
        dataSelectedManager.dataSelected();
    }
    public static void triggerDataTransfer(){
        ArrayList<Contact> selectedContacts = new ArrayList<>();
        for(Contact contact : contacts){
            if (contact.isSelected()){
                selectedContacts.add(contact);
            }
        }
        dataSelectedManager.sendSelectedContacts(selectedContacts);
    }
}

AppsManager.java

public class AppsManager {
    PackageManager packageManager;
    private String PACKAGE_NAME;
    public AppsManager(PackageManager packageManager,String PACKAGE_NAME) {
        this.packageManager = packageManager;
        this.PACKAGE_NAME = PACKAGE_NAME;
    }
    public ArrayList<App> getInstalledApps(){
        PackageManager packageManager = this.packageManager;
        ArrayList<App> apps = new ArrayList<>();
        List<PackageInfo> packs = packageManager.getInstalledPackages(0);
        for (int i = 0; i < packs.size(); i++){
            PackageInfo packageInfo = packs.get(i);
            if ((!isSystemApp(packageInfo)) && !packageInfo.packageName.equals(PACKAGE_NAME)){
                String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
                Drawable icon = packageInfo.applicationInfo.loadIcon(packageManager);
                String packages = packageInfo.applicationInfo.packageName;
                apps.add(new App(appName,icon,packages,false));
            }
        }
        return apps;
    }
    private boolean isSystemApp(PackageInfo packageInfo){
        return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
    }
}

ContactsManager.java

public class ContactsManager{
    ContentResolver contentResolver;
    public ContactsManager(ContentResolver contentResolver) {
        this.contentResolver = contentResolver;
    }
    public ArrayList<Contact> getContacts(){
        ContentResolver cr = contentResolver;
        ArrayList<Contact> contacts = new ArrayList<>();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
        if (cursor.getCount() > 0){
            while (cursor.moveToNext()){
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String phone = "";
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        phone = pCur.getString(
                                pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }
                    pCur.close();
                }
                Contact contact = new Contact(name,id,phone,false);
                contacts.add(contact);
            }
        }
        return contacts;
    }
}

FileManager.java

public class FileManager {
    private static final String TAG = "FileManager";
    Context context;
    public FileManager(Context context) {
        this.context = context;
    }
    public ArrayList<FileObject> readFiles(String path, ArrayList<FileObject> selectedFiles){
        ArrayList<FileObject> filesList = new ArrayList<>();
        File file = new File(path);
        File[] files = file.listFiles();
        for (File file1 : files){
            String name = file1.getName();
            String filePath = file1.getAbsolutePath();
            boolean isDirectory = file1.isDirectory();
            String fileSize = "";
            if (isDirectory){
                int count = file1.listFiles().length;
                if (count > 0){
                    fileSize = count + "";
                }
            }
            else{
                long fileSizeInBytes = file1.length();
                long fileSizeInKB = fileSizeInBytes / 1024;
                long fileSizeInMB = fileSizeInKB / 1024;
                if (fileSizeInMB >= 1){
                    fileSize = fileSizeInMB + " MB";
                }
                else{
                    fileSize = fileSizeInKB + " KB";
                }
            }
            boolean selected = isSelected(filePath,selectedFiles);
            String extension = "";
            if (isDirectory){
                extension = "none";
            }
            else{
                Log.d(TAG, "readFiles: " + filePath);
                String[] splitArray = filePath.split("\\.");
                Log.d(TAG, "readFiles: " + splitArray.length);
                extension = splitArray[splitArray.length - 1];
            }
            Drawable icon;
            if (isDirectory){
                icon = context.getResources().getDrawable(R.drawable.ic_folder_skin_24dp);
            }
            else{
                switch (extension){
                    case "pdf":
                        icon = context.getResources().getDrawable(R.drawable.ic_picture_as_pdf_red_24dp);
                        break;
                    default:
                        icon = context.getResources().getDrawable(R.drawable.ic_insert_drive_file_skin_24dp);
                        break;
                }
            }
            FileObject fileObject = new FileObject(name,filePath,icon,isDirectory,extension,fileSize,selected);
            filesList.add(fileObject);
        }
        return filesList;
    }
    boolean isSelected(String path, ArrayList<FileObject> selectedFiles){
        boolean isSelected = false;
        for (FileObject fileObject : selectedFiles){
            if (fileObject.getPath().equals(path)){
                isSelected = true;
            }
        }
            return isSelected;
    }

}
  • javascript:从Vue验证器构建自定义错误消息
  • go:一个案例可以执行多个案例吗?