package eu.deki.paste; import java.io.IOException; import android.os.AsyncTask; import android.content.Context; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.util.Log; import android.text.ClipboardManager; public abstract class PasteTask extends AsyncTask { private String errorMessage = "Fail"; protected Context parentActivity = null; public PasteTask(Context parent) { super(); parentActivity = parent; } @Override protected String doInBackground(String... params) { String title, content, expiration, result; if(params.length != 3) return null; title = params[0]; content = params[1]; expiration = params[2]; if(content.length() == 0) { errorMessage = parentActivity.getResources().getString(R.string.contentTooShort); cancel(false); return null; } try { result = paste(title, content, expiration); if(result == null) cancel(false); } catch(IOException ex) { cancel(false); errorMessage = ex.getLocalizedMessage(); result = errorMessage; Log.e("PasteIt", "doInBackground", ex); } return result; } private void copyToClipboard(String url) { ClipboardManager clipboard = (ClipboardManager) parentActivity.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(url); } @Override protected void onPostExecute(String result) { copyToClipboard(result); AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); String message = String.format(parentActivity.getResources().getString(R.string.pasteSuccessMessage), result); builder.setMessage(message); builder.setTitle(R.string.pasteSuccessTitle); builder.setPositiveButton("OK", null); builder.create().show(); } @Override protected void onCancelled() { AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); String message = String.format(parentActivity.getResources().getString(R.string.pasteFailMessage), errorMessage); builder.setMessage(message); builder.setTitle(R.string.pasteFailTitle); builder.setPositiveButton("OK", null); builder.create().show(); } protected abstract String paste(String title, String content, String delay) throws IOException; }