I am fairly new to Android development so I thought I would start off with a basic app. When a button is pressed, it copies a file to the location written in the code (see my code below). When I press the install button and the file is copied to its location, I want a toast message to display “Successfully Installed or Error while copying file”. How would I implement this?
public class TrialActivity extends Activity {
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runDialog(5);
}
private void runDialog(final int seconds)
{
progressDialog = ProgressDialog.show(this, "Please Wait...", "unpacking patch in progress");
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(seconds * 1000);
progressDialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
((Button)findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramView)
{
}
{
InputStream in = null;
OutputStream out = null;
String filename="savegame.bin";
try {
in = getResources().openRawResource(R.raw.savegame);
out = new FileOutputStream("/sdcard/Android/data/files/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
Message message = Message.obtain();
message.what = 1; // success message
mHandler.sendMessage(message);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
);
}
Handler mHandler = new Handler() {
public void handleMessage( Message msg )
{
Toast toast;
switch(msg.what)
{
case 1: // for success
toast = Toast.makeText(getBaseContext(), "Created By MRxBIGxSTUFF", Toast.LENGTH_SHORT);
toast.show();
break;
case 0: // for Error
toast = Toast.makeText(getBaseContext(), "Error... Application has shutdown", Toast.LENGTH_LONG);
toast.show();
break;
}
}
};
}
I recommend to use AsyncTask to run your process in background. Which doesn’t freeze the User Interface event the copying file size goes big.
You can show your progressbar while loading the operation.
I think this is one of the best way to handle with files(i.e copying,downloading etc)
Hope it helps