开发者

Create directory when application installed?

I would like to create a directory on the SD card of the device running my application when the application is installed, however I am not sure how to accomplish this. Does anyone have any ideas as to how I might create a directory 开发者_开发知识库at install time? Thanks in advance for any help.


Sunil,

This can't be done at install time, but it can be done on the first run...

This can be done by adding the following in your onCreate() method of your first Activity.

if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        Log.d("MyApp", "No SDCARD");
} else {
    File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"MyAppFolder");
    directory.mkdirs();
}

Good luck!


You are probably right that we can't do at the time of installation, but there is way in which we can do this. that is if we create our own application class and write your code in onCreate method of application then we can reduce redundant checking on every start up of application because onCreate method get called only when application created.

we can implement this like following

public class MyApplication extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        Log.d("MyApp", "No SDCARD");
        } 
        else {
            File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"MyAppFolder");
           directory.mkdirs();
    }
}

and we can use it by mentioning in menifest file

<application android:name=".MyApplication" android:icon="@drawable/icon" android:label="@string/app_name">
......
</application>


Good Day.One more hint you can use SharedPreferences.Here is how.

  1. Create one-time activity(E.g logo screen,welcome screen and etc)
  2. On that activity paste the code which will only create desired directory and folder
  3. Implement on one-time activity and next matching activity the shared preferences(see docs in google)
  4. Check through shared preferences whether your one-time activity was launched first time or no and you can skip that activity. Hope this helped.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜