Backup Activity : Activity « UI « Android






Backup Activity

     
package app.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

 class BackupTask extends AsyncTask<String,Void,Integer> {
    
    public interface CompletionListener {
        void onBackupComplete();
        void onRestoreComplete();
        void onError(int errorCode);
    }
    
    public static final int BACKUP_SUCCESS = 1;
    public static final int RESTORE_SUCCESS = 2;
    public static final int BACKUP_ERROR = 3;
    public static final int RESTORE_NOFILEERROR = 4;
    
    public static final String COMMAND_BACKUP = "backupDatabase";
    public static final String COMMAND_RESTORE = "restoreDatabase";
    
    private Context mContext;
    private CompletionListener listener;
    
    public BackupTask(Context context) {
        super();
        mContext = context;
    }
    
    public void setCompletionListener(CompletionListener aListener) {
        listener = aListener;
    }
    
    @Override
    protected Integer doInBackground(String... params) {
        File dbFile = mContext.getDatabasePath("mydb");
        File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        String command = params[0];
        if(command.equals(COMMAND_BACKUP)) {
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return BACKUP_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else if(command.equals(COMMAND_RESTORE)) {
            try {
                if(!backup.exists()) {
                    return RESTORE_NOFILEERROR;
                }
                dbFile.createNewFile();
                fileCopy(backup, dbFile);
                return RESTORE_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else {
            return BACKUP_ERROR;
        }
    }
    
    @Override
    protected void onPostExecute(Integer result) {

        switch(result) {
        case BACKUP_SUCCESS:
            if(listener != null) {
                listener.onBackupComplete();
            }
            break;
        case RESTORE_SUCCESS:
            if(listener != null) {
                listener.onRestoreComplete();
            }
            break;
        case RESTORE_NOFILEERROR:
            if(listener != null) {
                listener.onError(RESTORE_NOFILEERROR);
            }
            break;
        default:
            if(listener != null) {
                listener.onError(BACKUP_ERROR);
            }
        }
    }
    
    private void fileCopy(File source, File dest) throws IOException {
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(dest).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
}

public class Test extends Activity implements BackupTask.CompletionListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        SQLiteDatabase db = openOrCreateDatabase("mydb", Activity.MODE_PRIVATE, null);
        db.close();
    }
    
    @Override
    public void onResume() {
        super.onResume();
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
            BackupTask task = new BackupTask(this);
            task.setCompletionListener(this);
            task.execute(BackupTask.COMMAND_RESTORE);
        }
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
            BackupTask task = new BackupTask(this);
            task.execute(BackupTask.COMMAND_BACKUP);
        }
    }

    @Override
    public void onBackupComplete() {
        Toast.makeText(this, "Backup Successful", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(int errorCode) {
        if(errorCode == BackupTask.RESTORE_NOFILEERROR) {
            Toast.makeText(this, "No Backup to Restore", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Error: "+errorCode, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRestoreComplete() {
        Toast.makeText(this, "Restore Successful", Toast.LENGTH_SHORT).show();
    }
}

   
    
    
    
    
  








Related examples in the same category

1.Notification Activity
2.Timing Activity
3.Set content view from xml for Activity
4.More than one Activity
5.Find user control by using findViewById
6.A Simple Form
7.Link form with POJO
8.Life cycle
9.Comparing Android UI Elements to Swing UI Elements
10.add android:background = "#FFFF0000"
11.Rotation demo
12.Set activity screen Orientation
13.Check activity result
14.Activity lifecycle event
15.Activity key event
16.Allows the activity to manage the Cursor's lifecyle based on the activity’s lifecycle---
17.Activity configuration changed event
18.Check Activity result and onActivityResult
19.Phone Call Activity
20.Using Media Store Activity
21.External Storage Activity
22.Making Activity Go Full-Screen
23.Surface View Test Activity
24.Widget Preview Activity
25.This class provides a basic demonstration of how to write an Android activity.
26.This demonstrates the basic code needed to write a Screen activity
27.Example of removing yourself from the history stack after forwarding to another activity.
28.Fancy Blur Activity
29.Example of receiving a result from another activity.
30.Demonstrates required behavior of saving and restoring dynamic activity state
31.Securer Activity
32.This activity is an example of a simple settings screen that has default values.
33.Bind Click Action Activity
34.get ActivityManager
35.forward to another Activity
36.Request window features before setContentView
37.No code required here to attach the listener
38.Save data to Preference
39.Save instance state
40.onRetainNonConfigurationInstance
41.Create a user interface in code.
42.Redirect
43.Demonstrates how the various soft input modes impact window resizing.
44.extends Activity implements OnClickListener