精华内容
下载资源
问答
  • 偶尔遇到要获取文件路径的方案,给大家...// 在点击事件中跳转到系统文件管理器 public void onClick(View v){  Intent intent = new Intent();  intent.setAction(Intent.ACTION_GET_CONTENT);  int

    偶尔遇到要获取文件路径的方案,给大家提供一下喽

    效果图奉上


    //  在点击事件中跳转到系统文件管理器

    public void onClick(View v){
                    Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivityForResult(intent, 1100);
    }

    //  选择完毕后在onActivityResult方法中回调     从data中拿到文件路径
    protected void onActivityResult(int requestCode, int resultCode, Intent data)  {  
            if (resultCode == Activity.RESULT_OK)  
            {  
                Uri uri = data.getData();  
                tvUpload.setText(uri.toString()); 
            }  

    }  




    附上demo地址    点击打开链接

    展开全文
  • 在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。  在阎宏博士的《JAVA与模式》一书中...

    一、观察者模式:

      观察者模式(有时又被称为模型-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。

     

      在阎宏博士的《JAVA与模式》一书中开头是这样描述的:观察者模式是对象的行为模式,又叫发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。观察者设计模式定义了对象间的一种一对多的组合关系,以便一个对象的状态发生变化时,所有依赖于它的对象都得到通知并自动刷新。

     

    二、观察者模式结构图:

                    

     

    三、观察者模式所涉及的角色有:

      1、抽象主题(Subject)角色:抽象主题角色把所有对观察者对象的引用保存在一个聚集(比如ArrayList对象)里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象。

      2、具体主题(ConcreteSubject)角色:将有关状态存入具体观察者对象;在具体主题的内部状态改变时,给所有登记过的观察者发出通知。

      3、抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己,这个接口叫做更新接口。

      4、具体观察者(ConcreteObserver)角色:存储与主题的状态自恰的状态。具体观察者角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态 像协调。如果需要,具体观察者角色可以保持一个指向具体主题对象的引用。

     

    四、具体事例FileObserver:Android系统的文件管理

      GitHub源代码链接:https://github.com/doyee/FileObserver-android

    1. 观察者接口

    package custom.fileobserver;
    
    
    
    public interface FileListener {
    
        public void onFileCreated(String name);
    
        public void onFileDeleted(String name);
    
        public void onFileModified(String name);
    
        public void onFileRenamed(String oldName, String newName);
    
    }

    2、具体观察者

    /*
    
     * 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 custom.fileobserver;
    
    import android.os.Handler;
    
    import android.os.HandlerThread;
    
    import android.os.Process;
    
    import android.util.Log;
    
    
    
    
    
    import java.io.File;
    
    import java.io.FileFilter;
    
    import java.lang.ref.WeakReference;
    
    import java.util.HashMap;
    
    import java.util.Iterator;
    
    
    
    /**
    
     * Monitors files (using <a href="http://en.wikipedia.org/wiki/Inotify">inotify</a>)
    
     * to fire an event after files are accessed or changed by by any process on
    
     * the device (including this one).  FileObserver is an abstract class;
    
     * subclasses must implement the event handler {@link #onEvent(int, String)}.
    
     *
    
     * <p>Each FileObserver instance monitors a single file or directory.
    
     * If a directory is monitored, events will be triggered for all files and
    
     * subdirectories (recursively) inside the monitored directory.</p>
    
     *
    
     * <p>An event mask is used to specify which changes or actions to report.
    
     * Event type constants are used to describe the possible changes in the
    
     * event mask as well as what actually happened in event callbacks.</p>
    
     *
    
     * <p class="caution"><b>Warning</b>: If a FileObserver is garbage collected, it
    
     * will stop sending events.  To ensure you keep receiving events, you must
    
     * keep a reference to the FileObserver instance from some other live object.</p>
    
     */
    
    /**
    
     * 
    
     * @author Dai Dongsheng
    
     * Email: doyee@163.com
    
     * 
    
     */
    
    public abstract class FileObserver {
    
        /** Event type: Data was read from a file */
    
        public static final int ACCESS = 0x00000001;
    
        /** Event type: Data was written to a file */
    
        public static final int MODIFY = 0x00000002;
    
        /** Event type: Metadata (permissions, owner, timestamp) was changed explicitly */
    
        public static final int ATTRIB = 0x00000004;
    
        /** Event type: Someone had a file or directory open for writing, and closed it */
    
        public static final int CLOSE_WRITE = 0x00000008;
    
        /** Event type: Someone had a file or directory open read-only, and closed it */
    
        public static final int CLOSE_NOWRITE = 0x00000010;
    
        /** Event type: A file or directory was opened */
    
        public static final int OPEN = 0x00000020;
    
        /** Event type: A file or subdirectory was moved from the monitored directory */
    
        public static final int MOVED_FROM = 0x00000040;
    
        /** Event type: A file or subdirectory was moved to the monitored directory */
    
        public static final int MOVED_TO = 0x00000080;
    
        /** Event type: A new file or subdirectory was created under the monitored directory */
    
        public static final int CREATE = 0x00000100;
    
        /** Event type: A file was deleted from the monitored directory */
    
        public static final int DELETE = 0x00000200;
    
        /** Event type: The monitored file or directory was deleted; monitoring effectively stops */
    
        public static final int DELETE_SELF = 0x00000400;
    
        /** Event type: The monitored file or directory was moved; monitoring continues */
    
        public static final int MOVE_SELF = 0x00000800;
    
       
    
    
    
        public static final int UNMOUNT = 0x00002000;
    
        public static final int Q_OVERFLOW = 0x00004000;
    
        public static final int IGNORED = 0x00008000; 
    
    
    
        public static final int CLOSE = (CLOSE_WRITE | CLOSE_NOWRITE);
    
        public static final int MOVE  = (MOVED_FROM | MOVED_TO);
    
    
    
        public static final int ONLYDIR = 0x01000000;
    
        public static final int DONT_FOLLOW = 0x02000000;
    
        public static final int MASK_ADD = 0x20000000; 
    
        public static final int ISDIR   = 0x40000000 ;
    
        public static final int ONESHOT = 0x80000000; 
    
    
    
        /** Event mask: All valid event types, combined */
    
        public static final int ALL_EVENTS = ACCESS | MODIFY | ATTRIB | CLOSE_WRITE
    
                | CLOSE_NOWRITE | OPEN | MOVED_FROM | MOVED_TO | DELETE | CREATE
    
                | DELETE_SELF | MOVE_SELF;
    
        public static int FILE_CHANGED = CREATE | DELETE | MOVED_FROM | MOVED_TO | CLOSE_WRITE;/* MODIFY | ATTRIB*/;
    
        
    
        private static final String LOG_TAG = "FileObserver";
    
    
    
    
    
        private static class FolderFilter implements FileFilter{
    
            public boolean accept(File pathname) {
    
                return pathname.isDirectory();
    
            }
    
        }
    
        private static class ObserverThread extends Thread {
    
            private HashMap<Integer, WeakReference<Object>> mObservers = new HashMap<Integer, WeakReference<Object>>();
    
            private HashMap<Integer,String> mListPath = new HashMap<Integer,String>();
    
            private FolderFilter mFilter = new FolderFilter();
    
            private int m_fd;
    
    
    
            public ObserverThread() {
    
                super("FileObserver");
    
                m_fd = init();
    
            }
    
    
    
            public void run() {
    
                observe(m_fd);
    
            }
    
    
    
            public int startWatching(String observed, String path, int mask, FileObserver observer) {
    
                int wfd = startWatching(m_fd, path, mask);
    
    
    
                Integer i = new Integer(wfd);
    
                if (wfd <= 0) {
    
                    
    
                    return i;
    
                }
    
                
    
                synchronized (mObservers) {
    
                    mObservers.put(i, new WeakReference<Object>(observer));
    
                    mListPath.put(i, path.replaceFirst(observed, ""));
    
    
    
                    if(observer.mWatchSubDir){
    
                        File rootFolder = new File(path);
    
                        File[] childFolders = rootFolder.listFiles(mFilter);
    
                        if((childFolders != null))
    
                        {
    
                            for(int index = 0; index < childFolders.length; index++)
    
                                startWatching(observed, childFolders[index].getPath(), mask, observer);
    
                        }
    
                    }
    
                }
    
                
    
                return i;
    
            }
    
    
    
            public void stopWatching(int descriptor, FileObserver observer) {
    
                synchronized(mObservers)
    
                {
    
                    stopWatching(m_fd, descriptor);
    
                    mListPath.remove(descriptor);
    
                    mObservers.remove(descriptor);
    
    
    
                    Iterator <Integer> it = mListPath.keySet().iterator();
    
                    while(it.hasNext())
    
                    {
    
                        Integer fd = it.next();
    
                        if(mObservers.get(fd).get() == observer)
    
                        {
    
                            stopWatching(m_fd, fd);
    
                            it.remove();
    
                            mObservers.remove(fd);
    
                        }
    
                    }
    
                }
    
            }
    
    
    
            public void onEvent(int wfd, int mask, int cookie, String path) {
    
                // look up our observer, fixing up the map if necessary...
    
                FileObserver observer = null;
    
    
    
                synchronized (mObservers) {
    
                    WeakReference<Object> weak = mObservers.get(wfd);
    
                    if (weak != null) { // can happen with lots of events from a
    
                                        // dead wfd
    
                        observer = (FileObserver) weak.get();
    
                        if (observer == null) {
    
                            mObservers.remove(wfd);
    
                            mListPath.remove(wfd);
    
                        }
    
                    }
    
                }
    
    
    
                // ...then call out to the observer without the sync lock held
    
                if (observer == null) {
    
                    Log.i(LOG_TAG,"onEvent observer null ,return...");
    
                    return;
    
                }
    
    
    
                try {
    
                    String observed = observer.mPath ;
    
                    String newAbsPath = observed + mListPath.get(wfd);
    
                    if (path != null) {
    
                        if (newAbsPath.length() > 0) {
    
                            newAbsPath += "/";
    
                        }
    
                        newAbsPath += path;
    
                    }
    
    
    
                    if ((mask & (CREATE | ISDIR)) != 0) {
    
                        //auto to watch new created subdirectory
    
                        if(observer.mWatchSubDir){
    
                            startWatching(observed, newAbsPath, observer.mMask, observer);
    
                        }
    
                        
    
                    }
    
    
    
                    observer.onEvent(mask, cookie,newAbsPath);
    
                } catch (Throwable throwable) {
    
                    Log.wtf(LOG_TAG, "Unhandled exception in FileObserver "
    
                            + observer, throwable);
    
                }
    
    
    
            }
    
    
    
            private native int init();
    
            private native void observe(int fd);
    
            private native int startWatching(int fd, String path, int mask);
    
            private native void stopWatching(int fd, int wfd);
    
        }
    
    
    
       
    
        private static ObserverThread s_observerThread;
    
    
    
        static {
    
            try{
    
                System.loadLibrary("fileobserver_jni");
    
            }catch (UnsatisfiedLinkError e) {
    
                e.printStackTrace();
    
            }
    
            
    
            
    
            /*try {
    
                Thread.sleep(5000);
    
            } catch (InterruptedException e) {
    
                e.printStackTrace();
    
            }*/
    
            
    
            s_observerThread = new ObserverThread();
    
            s_observerThread.start();
    
        }
    
    
    
        // instance
    
        private String mPath;
    
        private Integer mDescriptor;
    
        private int mMask;
    
        private boolean mWatchSubDir;
    
        
    
        String mThreadName = FileObserver.class.getSimpleName();
    
        HandlerThread mThread;
    
        Handler mThreadHandler;
    
    
    
        /**
    
         * Equivalent to FileObserver(path, FileObserver.ALL_EVENTS).
    
         */
    
        public FileObserver(String path) {
    
            this(path, ALL_EVENTS);
    
            
    
        }
    
    
    
        public FileObserver(String path, int mask) {
    
            this(path,false,mask);
    
        }
    
        /**
    
         * Create a new file observer for a certain file or directory.
    
         * Monitoring does not start on creation!  You must call
    
         * {@link #startWatching()} before you will receive events.
    
         *
    
         * @param path The file or directory to monitor
    
         * @param watchSubDir If the sub directory need monitor ,set to true,default false
    
         * @param mask The event or events (added together) to watch for
    
         */
    
        public FileObserver(String path, boolean watchSubDir,int mask) {
    
            mPath = path;
    
            mMask = mask;
    
            mDescriptor = -1;
    
            mWatchSubDir = watchSubDir;
    
        }
    
    
    
        protected void finalize() {
    
            stopWatching();
    
        }
    
    
    
        /**
    
         * Start watching for events.  The monitored file or directory must exist at
    
         * this time, or else no events will be reported (even if it appears later).
    
         * If monitoring is already started, this call has no effect.
    
         */
    
        public void startWatching() {
    
            mThreadName = FileWatcher.class.getSimpleName();
    
            if (mThread == null || !mThread.isAlive()) {
    
                Log.i(LOG_TAG,"startFileWather new HandlerThread...");
    
                mThread = new HandlerThread(mThreadName,Process.THREAD_PRIORITY_BACKGROUND);
    
                mThread.setDaemon(true);
    
                mThread.start();
    
    
    
                mThreadHandler = new Handler(mThread.getLooper());
    
                mThreadHandler.post(new Runnable() {
    
                    @Override
    
                    public void run() {
    
                        Log.i(LOG_TAG,"startWatching mDescriptor:" + mDescriptor);
    
                        if (mDescriptor < 0) {
    
                            mDescriptor = s_observerThread.startWatching(mPath, mPath, mMask, FileObserver.this);
    
                            Log.i(LOG_TAG,"startWatching finished mDescriptor: " + mDescriptor);
    
                        }
    
                    }
    
                });
    
            }
    
    
    
        }
    
    
    
        /**
    
         * Stop watching for events.  Some events may be in process, so events
    
         * may continue to be reported even after this method completes.  If
    
         * monitoring is already stopped, this call has no effect.
    
         */
    
        public void stopWatching() {
    
            if(null != mThreadHandler && null != mThread && mThread.isAlive()){
    
                mThreadHandler.post(new Runnable() {
    
                    @Override
    
                    public void run() {
    
                        Log.i(LOG_TAG,"stopWatching mDescriptor:" + mDescriptor);
    
                        if (mDescriptor < 0) { 
    
                            Log.i(LOG_TAG,"stopWatching already stopped:" + mDescriptor);
    
                            return;
    
                        }
    
                        s_observerThread.stopWatching(mDescriptor, FileObserver.this);
    
                        mDescriptor = -1;
    
                        Log.i(LOG_TAG,"stopWatching finished:" + mDescriptor);
    
                        
    
                        mThreadHandler = null;
    
                        mThread.quit();
    
                        mThread = null;
    
                    }
    
                });
    
            }
    
        }
    
    
    
        /**
    
         * The event handler, which must be implemented by subclasses.
    
         *
    
         * <p class="note">This method is invoked on a special FileObserver thread.
    
         * It runs independently of any threads, so take care to use appropriate
    
         * synchronization!  Consider using {@link Handler#post(Runnable)} to shift
    
         * event handling work to the main thread to avoid concurrency problems.</p>
    
         *
    
         * <p>Event handlers must not throw exceptions.</p>
    
         *
    
         * @param event The type of event which happened
    
         * @param path The path, relative to the main monitored file or directory,
    
         *     of the file or directory which triggered the event
    
         */
    
        public abstract void onEvent(int event, int cookie,String path);
    
    
    
    }

    3、抽象主题类

    package custom.fileobserver;
    
    
    
    import java.util.Hashtable;
    
    
    
    import android.util.Log;
    
    /**
    
     * 
    
     * @author Dai Dongsheng
    
     * Email: doyee@163.com
    
     * FileWatcher support subdirectory(recursively)
    
     */
    
    public class FileWatcher extends FileObserver {
    
        FileListener mFileListener;
    
        Hashtable<Integer, String> mRenameCookies = new Hashtable<Integer, String>();
    
        public FileWatcher(String path) {
    
            this(path, ALL_EVENTS);
    
        }
    
    
    
        public FileWatcher(String path, int mask) {
    
            this(path, false,mask);
    
        }
    
        
    
        public FileWatcher(String path, boolean watchsubdir,int mask) {
    
            super(path, watchsubdir,mask);
    
        }
    
    
    
        public void setFileListener(FileListener fl){
    
            mFileListener = fl;
    
        }
    
        
    
        @Override
    
        public void onEvent(int event,int cookie,String path) {
    
            switch (event) {
    
            case ACCESS:
    
                Log.i("FileWatcher", "ACCESS: " + path);
    
                break;
    
            case ATTRIB:
    
                Log.i("FileWatcher", "ATTRIB: " + path);
    
                if(null != mFileListener){
    
                    mFileListener.onFileModified(path);
    
                }
    
                break;
    
            case CLOSE_NOWRITE:
    
                Log.i("FileWatcher", "CLOSE_NOWRITE: " + path);
    
                break;
    
            case CLOSE_WRITE:
    
                Log.i("FileWatcher", "CLOSE_WRITE: " + path);
    
                if(null != mFileListener){
    
                    mFileListener.onFileModified(path);
    
                }
    
                break;
    
            case CREATE:
    
                Log.i("FileWatcher", "CREATE: " + path);
    
                if(null != mFileListener){
    
                    mFileListener.onFileCreated(path);
    
                }
    
                break;
    
            case DELETE:
    
                Log.i("FileWatcher", "DELETE: " + path);
    
                if(null != mFileListener){
    
                    mFileListener.onFileDeleted(path);
    
                }
    
                break;
    
            case DELETE_SELF:
    
                Log.i("FileWatcher", "DELETE_SELF: " + path);
    
                if(null != mFileListener){
    
                    mFileListener.onFileDeleted(path);
    
                }
    
                break;
    
            case MODIFY:
    
                Log.i("FileWatcher", "MODIFY: " + path);
    
                if(null != mFileListener){
    
                    mFileListener.onFileModified(path);
    
                }
    
                break;
    
            case MOVE_SELF:
    
                Log.i("FileWatcher", "MOVE_SELF: " + path);
    
                break;
    
            case MOVED_FROM:
    
                Log.i("FileWatcher", "MOVED_FROM: " + path);
    
                mRenameCookies.put(cookie, path);
    
                break;
    
            case MOVED_TO:
    
                Log.i("FileWatcher", "MOVED_TO: " + path);
    
                if(null != mFileListener){
    
                    String oldName = mRenameCookies.remove(cookie);
    
                    mFileListener.onFileRenamed(oldName, path);
    
                }
    
                break;
    
            case OPEN:
    
                Log.i("FileWatcher", "OPEN: " + path);
    
                break;
    
            default:
    
                Log.i("FileWatcher", "DEFAULT(" + event + ") : " + path);
    
                switch(event - ISDIR){
    
                case ACCESS:
    
                    Log.i("FileWatcher", "ACCESS: " + path);
    
                    break;
    
                case ATTRIB:
    
                    Log.i("FileWatcher", "ATTRIB: " + path);
    
                    if(null != mFileListener){
    
                        mFileListener.onFileModified(path);
    
                    }
    
                    break;
    
                case CLOSE_NOWRITE:
    
                    Log.i("FileWatcher", "CLOSE_NOWRITE: " + path);
    
                    break;
    
                case CLOSE_WRITE:
    
                    Log.i("FileWatcher", "CLOSE_WRITE: " + path);
    
                    if(null != mFileListener){
    
                        mFileListener.onFileModified(path);
    
                    }
    
                    break;
    
                case CREATE:
    
                    Log.i("FileWatcher", "CREATE: " + path);
    
                    if(null != mFileListener){
    
                        mFileListener.onFileCreated(path);
    
                    }
    
                    break;
    
                case DELETE:
    
                    Log.i("FileWatcher", "DELETE: " + path);
    
                    if(null != mFileListener){
    
                        mFileListener.onFileDeleted(path);
    
                    }
    
                    break;
    
                case DELETE_SELF:
    
                    Log.i("FileWatcher", "DELETE_SELF: " + path);
    
                    if(null != mFileListener){
    
                        mFileListener.onFileDeleted(path);
    
                    }
    
                    break;
    
                case MODIFY:
    
                    Log.i("FileWatcher", "MODIFY: " + path);
    
                    if(null != mFileListener){
    
                        mFileListener.onFileModified(path);
    
                    }
    
                    break;
    
                case MOVE_SELF:
    
                    Log.i("FileWatcher", "MOVE_SELF: " + path);
    
                    break;
    
                case MOVED_FROM:
    
                    Log.i("FileWatcher", "MOVED_FROM: " + path);
    
                    mRenameCookies.put(cookie, path);
    
                    break;
    
                case MOVED_TO:
    
                    Log.i("FileWatcher", "MOVED_TO: " + path);
    
                    if(null != mFileListener){
    
                        String oldName = mRenameCookies.remove(cookie);
    
                        mFileListener.onFileRenamed(oldName, path);
    
                    }
    
                    break;
    
                case OPEN:
    
                    Log.i("FileWatcher", "OPEN: " + path);
    
                    break;
    
                }
    
                break;
    
            }
    
        }
    
    
    
    }

    4.具体主题类

    package custom.fileobserver;
    
    
    
    import android.app.Activity;
    
    import android.os.Bundle;
    
    import android.os.Environment;
    
    import android.util.Log;
    
    
    
    public class TestActivity extends Activity {
    
    
    
        FileWatcher mWatcher;
    
        final String TAG = TestActivity.class.getSimpleName();
    
        @Override
    
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
            
    
            String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
    
            String dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
    
            //mWatcher = new FileWatcher(sdcard,true,FileWatcher.FILE_CHANGED);
    
            mWatcher = new FileWatcher(dcim,true,FileWatcher.FILE_CHANGED);
    
            mWatcher.setFileListener(mFileListener);
    
            mWatcher.startWatching();
    
        }
    
    
    
        FileListener mFileListener = new FileListener(){
    
    
    
            @Override
    
            public void onFileCreated(String name) {
    
                Log.i(TAG, "onFileCreated " + name);
    
            }
    
    
    
            @Override
    
            public void onFileDeleted(String name) {
    
                Log.i(TAG, "onFileDeleted " + name);
    
            }
    
    
    
            @Override
    
            public void onFileModified(String name) {
    
                Log.i(TAG, "onFileModified " + name);
    
            }
    
    
    
            @Override
    
            public void onFileRenamed(String oldName, String newName) {
    
                Log.i(TAG, "onFileRenamed from: " + oldName + " to: " + newName);
    
            }
    
            
    
        };
    
        @Override
    
        protected void onResume() {
    
    
    
            super.onResume();
    
        }
    
    
    
        @Override
    
        protected void onPause() {
    
    
    
            super.onPause();
    
        }
    
    
    
        @Override
    
        protected void onUserLeaveHint() {
    
    
    
            super.onUserLeaveHint();
    
        }
    
    
    
        @Override
    
        protected void onStop() {
    
            super.onStop();
    
        }
    
    
    
        @Override
    
        protected void onDestroy() {
    
            mWatcher.stopWatching();
    
            super.onDestroy();
    
        }
    
    }

     

    五、观察者模式的优缺点

    优点:

    1、分离了观察者和被观察者,使他们属于不同的抽象层次,从而降低了系统的耦合性,提高系统的健壮性和稳定性

    2、由于分离了观察者与被观察者,当系统需要增加或删除新的模式的时候,不需要对原有的代码进行修改,而是只用添加或删除观察者,从而提高了系统的可扩展性。

    3、观察者模式支持广播通讯。被观察者会向所有的登记过的观察者发出通知。

    缺点:

    1、如果一个被观察者对象有很多直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。

    2、如果对观察者的通知是通过另外的线程进行异步投递的话,系统必须保证投递是以自恰的方式进行的。

    3、虽然观察者模式可以随时使观察者知道所观察的对象发生了变化,但是观察者模式没有相应的机制使观察者知道所观察的对象是怎么发生变化的。

    4、如果在被观察者之间有循环依赖的话,被观察者会触发它们之间进行循环调用,导致系统崩溃。在使用观察考模式时要特别注意这一点。

     

    转载于:https://www.cnblogs.com/gyuan/p/9845342.html

    展开全文
  • 1.需求分析1.查找文件功能:可以根据指定的目录名与待查找的文件,在指定目录中进行查找,并返回结果2..实现文件的拷贝与粘贴功能3.实现文本类文件(.txt, ....在安卓系统上实现2.本组课题及本人任务安卓文件资源管...

    1.需求分析

    1.查找文件功能:可以根据指定的目录名与待查找的文件,在指定目录中进行查找,并返回结果

    2..实现文件的拷贝与粘贴功能

    3.实现文本类文件(.txt, .java, .ini, .bat, )的预览功能(比如实现对前100行文本在某个小窗口中进行预览)

    4.实现文件的重命名功能

    5..实现对某个文件夹进行统计功能(如统计文件夹中文件数目)

    6.在安卓系统上实现

    2.本组课题及本人任务

    安卓文件资源管理器

    1.实现文本类文件(.txt, .java, .ini, .bat, )的预览功能(比如实现对前100行文本在某个小窗口中进行预览)

    2.文件或文件夹重命名

    3.在安卓系统上实现

    3.总体设计(概要设计)

    主要设计为Folder类和Filel类

    e1103c5af90b6a155a782d3adae2c3fe.png

    Folder类

    提供绝对路径为参数获取对象

    可获得目录的各种信息

    并提供格式化size数据的方法

    3349baa16372935f52b867a7ede5be10.png

    Filel类

    直接继承File类,简化设计

    提供复制文件或为文件夹的方法

    文件和文件夹操作流程图

    467b673d2a12dc53fbe81f96e953c86b.png

    APP基于安卓API18

    主Activiy继承于ListView直接显示根目录

    视图使用Listview与继承自BaseAdapter的自定义适配器组合

    适配器getview中使用convertView,holder静态类加快UI流畅性

    3本人负责的主要功能展示与代码分析

    1.实现文本类文件(.txt, .java, .ini, .bat, )的预览功能(比如实现对前100行文本在某个小窗口中进行预览)

    0a04d51389e9eec03b419fe1b8fc58a6.png

    c0dee3e1609a0454d03e8f81eda474f3.png

    2.实现文件的重命名功能

    3ec64edc831b7b42f8a2e215685b42de.png

    3.在安卓系统上实现

    05bb6886c994dd7580b2cfc5f13d077b.png

    78863874a04c44fac6129783440c4a0d.png

    4.测试与改进

    使用多线程搜索文件

    利用外部应用打开音频,视频,图片文件

    删除文件

    5附录:完整、可运行代码(不打印,电子版需提供)

    MainActivity.java

    public class MainActivity extends ListActivity {

    private static final String ROOT_PATH = "/";

    private static String NOW_PATH;

    private ImageButton bt_search;

    //存储文件名称

    private ArrayList FileName = null;

    //存储文件路径

    private ArrayList FilePath = null;

    //重命名布局xml文件显示dialog

    private View view;

    private EditText v_filename;

    private EditText editText;

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    //显示文件列表

    showFileDir(ROOT_PATH);

    bt_search = (ImageButton)findViewById(R.id.bt_search);

    bt_search.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    v_filename = (EditText)findViewById(R.id.filename);

    Intent intent = new Intent(MainActivity.this,Search.class);

    intent.putExtra("path", NOW_PATH);

    intent.putExtra("filename", v_filename.getText().toString());

    startActivity(intent);

    }

    });

    //长按事件

    getListView().setOnItemLongClickListener(new OnItemLongClickListener(){

    public boolean onItemLongClick(AdapterView parent, View view, int position,long id) {

    String path = FilePath.get(position);

    File file = new File(path);

    // 文件存在并可读

    if (file.exists() && file.canRead()) {

    if (file.isDirectory()) {

    //处理目录

    dirHandle(file);

    } else {

    //处理文件

    fileHandle(file);

    }

    }

    //没有权限

    else {

    Resources res = getResources();

    new AlertDialog.Builder(MainActivity.this).setTitle("提示")

    .setMessage(res.getString(R.string.no_permission))

    .setPositiveButton("OK", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    Toast.makeText(getApplicationContext(), "没有权限", Toast.LENGTH_SHORT).show();

    }

    }).show();

    }

    return true;

    }

    });

    showFileDir(NOW_PATH);

    }

    /**

    * 点击事件

    * @param l

    * @param v

    * @param position

    * @param id

    */

    @Override

    protected void onListItemClick(ListView l, View v, int position, long id) {

    String path = FilePath.get(position);

    File file = new File(path);

    // 文件存在并可读

    if (file.exists() && file.canRead()) {

    if (file.isDirectory()) {

    //显示子目录及文件

    showFileDir(path);

    } else {

    //处理文件

    fileHandle(file);

    }

    }

    //没有权限

    else {

    Resources res = getResources();

    new AlertDialog.Builder(this).setTitle("提示")

    .setMessage(res.getString(R.string.no_permission))

    .setPositiveButton("OK", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    Toast.makeText(getApplicationContext(), "没有权限", Toast.LENGTH_SHORT).show();

    }

    }).show();

    }

    super.onListItemClick(l, v, position, id);

    }

    /**

    * 文件处理

    * @param file

    */

    private void fileHandle(final File file) {

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

    @SuppressWarnings("deprecation")

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // 打开文件

    if (which == 0) {

    openFile(file);

    }

    //重命名

    else if (which == 1) {

    LayoutInflater factory = LayoutInflater.from(MainActivity.this);

    view = factory.inflate(R.layout.rename_dialog, null);

    editText = (EditText) view.findViewById(R.id.editText);

    editText.setText(file.getName());

    DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated method stub

    String modifyName = editText.getText().toString();

    final String fpath = file.getParentFile().getPath();

    final File newFile = new File(fpath + "/" + modifyName);

    if (newFile.exists()) {

    //排除没有修改情况

    if (!modifyName.equals(file.getName())) {

    new AlertDialog.Builder(MainActivity.this)

    .setTitle("注意!")

    .setMessage("文件名已存在,是否覆盖?")

    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    if (file.renameTo(newFile)) {

    showFileDir(fpath);

    displayToast("重命名成功!");

    } else {

    displayToast("重命名失败!");

    }

    }

    })

    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    }

    })

    .show();

    }

    } else {

    if (file.renameTo(newFile)) {

    showFileDir(fpath);

    displayToast("重命名成功!");

    } else {

    displayToast("重命名失败!");

    }

    }

    }

    };

    AlertDialog renameDialog = new AlertDialog.Builder(MainActivity.this).create();

    renameDialog.setView(view);

    renameDialog.setButton("确定", listener2);

    renameDialog.setButton2("取消", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated method stub

    }

    });

    renameDialog.show();

    }

    //拷贝文件

    else if (which == 2){

    Intent intent = new Intent(MainActivity.this,Copy.class);

    intent.putExtra("soupath", file.getPath());

    intent.putExtra("isdel", false);

    startActivity(intent);

    }

    //删除文件

    else if (which == 3 ){

    Intent intent = new Intent(MainActivity.this,Copy.class);

    intent.putExtra("soupath", file.getPath());

    intent.putExtra("isdel", true);

    startActivity(intent);

    showFileDir(ROOT_PATH);

    }

    else {

    new AlertDialog.Builder(MainActivity.this)

    .setTitle("注意!")

    .setMessage("确定要删除此文件吗?")

    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    if (file.delete()) {

    //更新文件列表

    showFileDir(file.getParent());

    displayToast("删除成功!");

    } else {

    displayToast("删除失败!");

    }

    }

    })

    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    }

    }).show();

    }

    }

    };

    //选择文件时,弹出操作选项对话框

    String type = MyAdapter.getMIMEType(file);

    String[] menu = {"打开文件", "重命名", "拷贝","剪切","删除文件",};

    if(type=="text"){

    menu[0] = "预览";

    }

    new AlertDialog.Builder(MainActivity.this)

    .setTitle("请选择要进行的操作!")

    .setItems(menu, listener)

    .setPositiveButton("取消", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {

    }

    }).show();

    }

    /**

    * 扫描显示文件列表

    * @param path

    */

    private void showFileDir(String path) {

    FileName = new ArrayList();

    FilePath = new ArrayList();

    File file = new File(path);

    NOW_PATH = path;

    File[] files = file.listFiles();

    //如果当前目录不是根目录

    if (!ROOT_PATH.equals(path)) {

    FileName.add("rot");

    FilePath.add(ROOT_PATH);

    FileName.add("last");

    FilePath.add(file.getParent());

    }

    //添加所有文件

    for (File f : files) {

    FileName.add(f.getName());

    FilePath.add(f.getPath());

    }

    this.setListAdapter(new MyAdapter(this, FileName, FilePath));

    }

    /**

    * 文件夹处理

    * @param file

    */

    public void dirHandle(final File file){

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated method stub

    if(which == 0){

    Intent intent = new Intent(MainActivity.this,Copy.class);

    intent.putExtra("soupath", file.getPath());

    intent.putExtra("isdel", false);

    startActivity(intent);

    }

    else if (which == 1){

    Intent intent = new Intent(MainActivity.this,Copy.class);

    intent.putExtra("soupath", file.getPath());

    intent.putExtra("isdel", true);

    startActivity(intent);

    showFileDir(ROOT_PATH);

    }

    else if (which == 2){

    Intent intent = new Intent(MainActivity.this,DirDetail.class);

    intent.putExtra("path",file.getPath());

    startActivity(intent);

    }else {

    final Folder folder = new Folder(file.getPath());

    new AlertDialog.Builder(MainActivity.this)

    .setTitle("注意!")

    .setMessage("确定删除文件夹及内部所有文件吗?")

    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    if (folder.delete()) {

    //更新文件列表

    showFileDir(file.getParent());

    displayToast("删除成功!");

    } else {

    displayToast("删除失败!");

    }

    }

    })

    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    }

    }).show();

    }

    }

    };

    String[] menu = {"拷贝","剪切","详情","删除"};

    new AlertDialog.Builder(MainActivity.this)

    .setTitle("请选择要进行的操作!")

    .setItems(menu, listener)

    .setPositiveButton("取消", listener = new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated method stub

    }

    }).show();

    }

    //打开文件

    /**

    * 打开文件

    * @param file

    */

    private void openFile(File file) {

    Intent intent = new Intent();

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    intent.setAction(android.content.Intent.ACTION_VIEW);

    String type = Mydapter.getMIMEType(file);

    if(file.isDirectory()){

    }

    else{

    if(type.equals("text")){

    intent = new Intent(MainActivity.this,Preview.class);

    intent.putExtra("path", file.getPath());

    }

    else{

    type += "/*";

    intent.setDataAndType(Uri.fromFile(file), type);

    }

    }

    startActivity(intent);

    }

    /**

    * 显示提示消息

    * @param message

    */

    private void displayToast(String message) {

    Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();

    }

    /**

    * back键监听

    */

    public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

    android.os.Process.killProcess(android.os.Process.myPid());

    return true;

    } else {

    return super.onKeyDown(keyCode, event);

    }

    }

    }

    MyAdapter.java

    public class MyAdapter extends BaseAdapter {

    private LayoutInflater inflater;

    private Bitmap directory, file,text;

    //存储文件名称

    private ArrayList names = null;

    //存储文件路径

    private ArrayList paths = null;

    //参数初始化

    public MyAdapter(Context context, ArrayList na, ArrayList pa) {

    names = na;

    paths = pa;

    directory = BitmapFactory.decodeResource(context.getResources(), R.drawable.dir);

    file = BitmapFactory.decodeResource(context.getResources(), R.drawable.file);

    text = BitmapFactory.decodeResource(context.getResources(), R.drawable.text);

    inflater = LayoutInflater.from(context);

    }

    @Override

    public int getCount() {

    // TODO Auto-generated method stub

    return names.size();

    }

    @Override

    public Object getItem(int position) {

    // TODO Auto-generated method stub

    return names.get(position);

    }

    @Override

    public long getItemId(int position) {

    // TODO Auto-generated method stub

    return position;

    }

    @Override

    public View getView(int position, View convertView, ViewGroup parent) {

    // TODO Auto-generated method stub

    ViewHolder holder;

    //如果缓存convertView为空,则需要创建View

    if (null == convertView) {

    //根据自定义的Item布局加载布局

    convertView = inflater.inflate(R.layout.file, null);

    holder = new ViewHolder();

    holder.text = (TextView) convertView.findViewById(R.id.listitem);

    holder.image = (ImageView) convertView.findViewById(R.id.imageView);

    //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag

    convertView.setTag(holder);

    } else {

    //取出tag

    holder = (ViewHolder) convertView.getTag();

    }

    File f = new File(paths.get(position).toString());

    if (names.get(position).equals("rot")) {

    holder.text.setText("根目录");

    holder.image.setImageBitmap(directory);

    } else if (names.get(position).equals("last")) {

    holder.text.setText("上一级目录");

    holder.image.setImageBitmap(directory);

    } else {

    holder.text.setText(f.getName());

    if (f.isDirectory()) {

    holder.image.setImageBitmap(directory);

    } else if (f.isFile()) {

    if(getMIMEType(f).equals("text")){

    holder.image.setImageBitmap(text);

    }else{

    holder.image.setImageBitmap(file);

    }

    } else {

    System.out.println(f.getName());

    }

    }

    return convertView;

    }

    /* 使用 ViewHolder 的关键好处是缓存了显示数据的视图(View),加快了 UI 的响应速度。

    当我们判断 convertView == null 的时候,如果为空,就会根据设计好的List的Item布局(XML)

    来为convertView赋值,并生成一个viewHolder来绑定converView里面的各个View控件(XML布局里面的那些控件)

    再用convertView的setTag将viewHolder设置到Tag中,以便系统第二次绘制ListView时从Tag中取出。

    如果convertView不为空的时候,就会直接用convertView的getTag(),来获得一个ViewHolder*/

    private class ViewHolder {

    private TextView text;

    private ImageView image;

    }

    public static String getMIMEType(File file) {

    String type = "";

    String name = file.getName();

    //文件扩展名

    String end = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();

    if (end.equals("m4a") || end.equals("mp3") || end.equals("wav")) {

    type = "audio";

    } else if (end.equals("mp4") || end.equals("3gp")) {

    type = "video";

    } else if (end.equals("jpg") || end.equals("png") || end.equals("jpeg") || end.equals("bmp") || end.equals("gif")) {

    type = "image";

    } else if(end.equals("txt") || end.equals("java") || end.equals("ini") || end.equals("bat")){

    type = "text";

    }

    else {

    type = "*";

    }

    return type;

    }

    }

    展开全文
  • 安卓文件管理

    2013-05-30 21:51:41
    安卓系统可用的re管理器,可以用于管理文件
  • 【实例简介】实验描述:Android系统并不自带文件管理器,但是很多情况下,我们有从SD卡中打开文件的需要,怎么办?相信大家都比较习惯Windows下操作文件和文件夹的方式,那么Android下是否也有类似的工具呢?答案是...

    【实例简介】

    实验描述:

    Android系统并不自带文件管理器,但是很多情况下,我们有从SD卡中打开文件的需要,怎么办?相信大家都比较习惯Windows下操作文件和文件夹的方式,那么Android下是否也有类似的工具呢?答案是必须有。本次实验我们将要开发的应用就是Android平台下的文件管理器。

    基于Android平台的文件管理器,我们借鉴Windows,从用户实际使用需求出发,主要实现的功能有:

    1)浏览任意目录下的文件及文件夹

    2)打开文件

    3)新建文件

    4)删除文件

    5)复制文件

    6)对文件重命名

    7)在当前目录或者整个目录进行搜索

    8)返回上一级以及根目录。

    【实例截图】

    29e2371415828979ec16593790265798.png

    【核心代码】

    /**注册广播*/

    private IntentFilter filter;

    private FileBroadcast fileBroadcast;

    private IntentFilter intentFilter;

    private SearchBroadCast serviceBroadCast;

    @Override

    protected void onStart() {

    // TODO Auto-generated method stub

    super.onStart();

    filter = new IntentFilter();

    filter.addAction(FileService.FILE_SEARCH_COMPLETED);

    filter.addAction(FileService.FILE_NOTIFICATION);

    intentFilter = new IntentFilter();

    intentFilter.addAction(KEYWORD_BROADCAST);

    if(fileBroadcast == null){

    fileBroadcast = new FileBroadcast();

    }

    if(serviceBroadCast == null){

    serviceBroadCast = new SearchBroadCast();

    }

    this.registerReceiver(fileBroadcast, filter);

    this.registerReceiver(serviceBroadCast, intentFilter);

    }

    @Override

    protected void onDestroy() {

    // TODO Auto-generated method stub

    super.onDestroy();

    fileNames.clear();

    filePaths.clear();

    this.unregisterReceiver(fileBroadcast);

    this.unregisterReceiver(serviceBroadCast);

    }

    private String action;

    class FileBroadcast extends BroadcastReceiver{

    @Override

    public void onReceive(Context context, Intent intent) {

    // TODO Auto-generated method stub

    action = intent.getAction();

    if(FileService.FILE_SEARCH_COMPLETED.equals(action)){

    fileNames = intent.getStringArrayListExtra("fileNamesList");

    filePaths = intent.getStringArrayListExtra("filePathsList");

    Toast.makeText(MainActivity.this, "搜索完毕!", Toast.LENGTH_SHORT).show();

    //这里搜索完毕之后应该弹出一个弹出框提示用户要不要显示数据

    searchCompletedDialog("搜索完毕,是否马上显示结果?");

    getApplicationContext().stopService(serviceIntent);//当搜索完毕的时候停止服务,然后在服务中取消通知

    // 点击通知栏跳转过来的广播

    }else if(FileService.FILE_NOTIFICATION.equals(action)){//点击通知回到当前Activity,读取其中信息

    String mNotification = intent.getStringExtra("notification");

    Toast.makeText(MainActivity.this, mNotification, Toast.LENGTH_LONG).show();

    searchCompletedDialog("你确定要取消搜索吗?");

    }

    }

    }

    //搜索完毕和点击通知过来时的提示框

    private void searchCompletedDialog(String message){

    Builder searchDialog = new AlertDialog.Builder(MainActivity.this)

    .setTitle("提示")

    .setMessage(message)

    .setPositiveButton("确定", new OnClickListener(){

    public void onClick(DialogInterface dialog,int which) {

    //当弹出框时,需要对这个确定按钮进行一个判断,因为要对不同的情况做不同的处理(2种情况)

    // 1.搜索完毕

    // 2.取消搜索

    if(FileService.FILE_SEARCH_COMPLETED.equals(action)){

    if(fileNames.size() == 0){

    Toast.makeText(MainActivity.this, "无相关文件/文件夹!", Toast.LENGTH_SHORT).show();

    setListAdapter(new FileAdapter(MainActivity.this,fileNames,filePaths));//清空列表

    }else{

    //显示文件列表

    setListAdapter(new FileAdapter(MainActivity.this,fileNames,filePaths));

    }

    }else{

    //设置搜索标志为true,

    isComeBackFromNotification = true;

    //关闭服务,取消搜索

    getApplicationContext().stopService(serviceIntent);

    }

    }

    })

    .setNegativeButton("取消", null);

    searchDialog.create();

    searchDialog.show();

    }

    public void paste(){

    final String filePath1 = oriFilePath;

    final String filePath2 = currentPath File.separator oriFileName;

    if(isCopy&&!filePath1.equals(filePath2)){

    if(!new File(filePath2).exists()){

    copyFile(filePath1,filePath2);

    traversalFileList(currentPath);

    }else{

    OnClickListener listener = new OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated method stub

    copyFile(filePath1, filePath2);

    traversalFileList(currentPath);

    Toast.makeText(getApplicationContext(), "文件覆盖成功!", 1000).show();

    }

    };

    new AlertDialog.Builder(MainActivity.this)

    .setTitle("温馨提示")

    .setMessage("文件已经存在,是否覆盖?")

    .setPositiveButton("确定", listener)

    .setNeutralButton("取消", null).show();

    }

    }else{

    Toast.makeText(getApplicationContext(), "请先复制文件!", 1000).show();

    }

    }

    public void copyFile(String filePath1,String filePath2){

    try {

    FileInputStream fin = new FileInputStream(new File(filePath1));

    FileOutputStream fout = new FileOutputStream(new File(filePath2));

    int index;

    while((index = fin.read())!=-1){

    fout.write(index);

    }

    traversalFileList(currentPath);

    if(fin!=null){

    fin.close();

    }

    if(fout!=null){

    fout.close();

    }

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    public void createFile(){

    fileCheckedId = 2;

    final LayoutInflater ll = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final LinearLayout layout = (LinearLayout)ll.inflate(R.layout.create_dialog,null);

    radioGroup1 = (RadioGroup)layout.findViewById(R.id.radioGroup1);

    final RadioButton createFileButton = (RadioButton)layout.findViewById(R.id.createFile);

    final RadioButton createFolderButton = (RadioButton)layout.findViewById(R.id.createFolder);

    createFolderButton.setChecked(true);

    radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override

    public void onCheckedChanged(RadioGroup group, int checkedId) {

    // TODO Auto-generated method stub

    if(checkedId == createFileButton.getId()){

    fileCheckedId = 1;

    }else if(checkedId == createFolderButton.getId()){

    fileCheckedId = 2;

    }

    }

    });

    Builder builder = new AlertDialog.Builder(MainActivity.this)

    .setView(layout)

    .setTitle("新建")

    .setPositiveButton("创建", new OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated method stub

    fileNameEditText = (EditText)layout.findViewById(R.id.createFileName);

    createFileNameStr = fileNameEditText.getText().toString();

    if(fileCheckedId == 1){

    try {

    createFile = new File(currentPath File.separator createFileNameStr ".txt");

    createFile.createNewFile();

    traversalFileList(currentPath);

    } catch (IOException e) {

    // TODO Auto-generated catch block

    Toast.makeText(MainActivity.this, "文件拼接出错", 1000).show();

    }

    }else if(fileCheckedId == 2){

    createFile = new File(currentPath File.separator createFileNameStr);

    if(!createFile.exists()&&!createFile.isDirectory()&&createFileNameStr.length()!=0){

    if(createFile.mkdirs()){

    traversalFileList(currentPath);

    }else{

    Toast.makeText(MainActivity.this, "创建失败,可能是系统权限不够,root一下?!", 1000).show();

    }

    }else{

    Toast.makeText(MainActivity.this, "文件名为空,还是重名了呢?", 1000).show();

    }

    }

    }

    }).setNeutralButton("取消", null);

    builder.show();

    }

    展开全文
  • 安卓 通过intent调用系统文件管理器打开指定路径目录 转 https://blog.csdn.net/qq_34161388/article/details/78586247 当我们知道一个文件的路径,如何调用系统文件管理器显示它的位置呢。 ...
  • [PConline应用]以前说起iOS里的文件管理,大家都会直摇头,就算是到了现在系统文件管理器,也只能称为勉强可用。不过,这可能是使用方式不对,iOS已经进一步开放了文件管理权限,其实现在iOS中也有好用的第三方...
  • 我认为最好的文件管理器,除了支持双面板操作、收藏夹之外,还有几个非常好的地方: 1、压缩文档无需解压,可以直接浏览,内置有强大的文本显示、图片显示插件,压缩文档中一般文件都可以直接打开; 2、支持网络功能...
  • 支持htcg8等自能手机的文件管理,可以目录浏览自由管理安装软件
  • 读取文件(N以上无需存储权限) 为兼容Android N以下设备,需要检查存储权限 在AndroidManifest.xml中添加如下声明(位于application标签之外) <uses-permission android:name="android.permission.READ_...
  • 安卓系统文件夹及其文件解析 打开Android文件管理器,会发现里面数十个英文名称命名的文件夹罗列其中,很多功能我们可以从其名字上略有所知,内部大批量的文件却让我们有些一头雾水。这些文件是什么?有什么用?...
  • 安卓手机超强文件管理器。Root后,能删除定制系统中的垃圾软件。
  • android studio 开发获取手机文件系统.rar,太多无法一一验证是否可用,程序如果跑不起来需要自调,部分代码功能进行参考学习。
  • RE管理器 2.3安卓系统

    热门讨论 2013-10-16 12:18:15
    RE管理器 2.3安卓系统 汉化版Root Explorer这款Android文件管理器的霸主几乎无人不知无人不晓。这是获取ROOT权限之后必装的文件管理
  • 市面上很多人都在使用苹果手机、安卓手机,现在越来越多的人购买苹果手机了。实际上,苹果手机与我们常用的安卓...苹果文件管理在哪里 步骤1、苹果手机是没有文件管理功能的,这是IOS系统的一个特点,IOS系统是不...
  • 360度LES文件浏览器功能可谓是非常强大,可以对文件或文件夹进行新建、复制、剪切、删除、移动、搜索等操作。支持多标签页,能设置... 这是目前Android上最具口碑的ROOT级别文件管理器,用于读写系统和保护目录,是...
  • 安卓 学生管理系统

    2015-12-17 17:10:14
    学生管理系统实现数据库和文件读取 交作业 供参考

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 743
精华内容 297
关键字:

安卓系统文件管理