如何添加进度条备份android中的联系人

时间:2016-08-10 07:51:09

标签: android mobile

我是android开发新手我打算为备份联系人设计android应用程序。我需要为备份联系人添加进度条,这里有什么可能是我的代码

public class MainActivity extends AppCompatActivity {
Button backup,restore;
String vfile;
FileOutputStream mFileOutputStream = null;
Cursor cursor;
ArrayList<String> vCard ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    backup=(Button)findViewById(R.id.btnbkp);
    restore=(Button)findViewById(R.id.btnres);

    vfile = "contacts.vcf";
    final String storage_path = Environment.getExternalStorageDirectory().toString() +"/"+ vfile;
    final File f = new File(storage_path);

    backup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if (!f.exists())
                    f.createNewFile();
                mFileOutputStream = new FileOutputStream(storage_path, false);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            getVcardString();
        }
    });
    restore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent = new Intent();

            final MimeTypeMap mime = MimeTypeMap.getSingleton();
            String tmptype = mime.getMimeTypeFromExtension("vcf");
            final File file = new File(Environment.getExternalStorageDirectory().toString() + "/contacts.vcf");

            intent.setDataAndType(Uri.fromFile(file), tmptype);
            startActivity(intent);
        }
    });

}
private void getVcardString()
{
    vCard = new ArrayList<String>();
    cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    if(cursor!=null&&cursor.getCount()>0)
    {
        cursor.moveToFirst();
        for(int i =0;i<cursor.getCount();i++)
        {

            get(cursor);
            Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
            cursor.moveToNext();
        }

    }
    else
    {
        Log.d("TAG", "No Contacts in Your Phone");
    }
    try
    {
        mFileOutputStream.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public void get(Cursor cursor)
{
    //cursor.moveToFirst();
    String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
    AssetFileDescriptor fd;
    try
    {
        fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
        FileInputStream fis = fd.createInputStream();
        byte[] buf = new byte[(int) fd.getDeclaredLength()];
        fis.read(buf);
        String vcardstring= new String(buf);
        vCard.add(vcardstring);

        mFileOutputStream.write(vcardstring.toString().getBytes());

    }
    catch (Exception e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

上面是我的应用程序的代码,我想为应用程序中的备份联系人添加进度条

1 个答案:

答案 0 :(得分:0)

使用AsyncTask进行长时间和后台操作,并在onPreExecute()中显示进度条,在dismiss() onPostExecute()中显示代码。

public class MainActivity extends AppCompatActivity {
    Button backup, restore;
    String vfile;
    FileOutputStream mFileOutputStream = null;
    Cursor cursor;
    ArrayList<String> vCard;
    File f;
    String storage_path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backup = (Button) findViewById(R.id.btnbkp);
        restore = (Button) findViewById(R.id.btnres);

        vfile = "contacts.vcf";
        storage_path = Environment.getExternalStorageDirectory().toString() + "/" + vfile;
        f = new File(storage_path);

        backup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new LongOperation().execute("");

            }
        });
        restore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent();

                final MimeTypeMap mime = MimeTypeMap.getSingleton();
                String tmptype = mime.getMimeTypeFromExtension("vcf");
                final File file = new File(Environment.getExternalStorageDirectory().toString() + "/contacts.vcf");

                intent.setDataAndType(Uri.fromFile(file), tmptype);
                startActivity(intent);
            }
        });

    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        ProgressDialog progress;

        @Override
        protected void onPreExecute() {
            progress = new ProgressDialog(MainActivity.this);
            progress.setMessage("Loading.... ");
            progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progress.setIndeterminate(true);
            progress.setProgress(0);
            progress.show();
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                if (!f.exists())
                    f.createNewFile();
                mFileOutputStream = new FileOutputStream(storage_path, false);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            getVcardString();
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            progress.dismiss();
        }

    }

    private void getVcardString() {
        vCard = new ArrayList<String>();
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {

                get(cursor);
                Log.d("TAG", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));
                cursor.moveToNext();
            }

        } else {
            Log.d("TAG", "No Contacts in Your Phone");
        }
        try {
            mFileOutputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void get(Cursor cursor) {
        //cursor.moveToFirst();
        String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
        AssetFileDescriptor fd;
        try {
            fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
            FileInputStream fis = fd.createInputStream();
            byte[] buf = new byte[(int) fd.getDeclaredLength()];
            fis.read(buf);
            String vcardstring = new String(buf);
            vCard.add(vcardstring);

            mFileOutputStream.write(vcardstring.toString().getBytes());

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }


}