List of usage examples for android.os Handler sendEmptyMessage
public final boolean sendEmptyMessage(int what)
From source file:org.anurag.compress.ExtractTarFile.java
public ExtractTarFile(final Context ctx, final Item zFile, final int width, String extractDir, final File file, final int mode) { // TODO Auto-generated constructor stub running = false;/*from w w w.ja v a2 s . c om*/ errors = false; prog = 0; read = 0; final Dialog dialog = new Dialog(ctx, Constants.DIALOG_STYLE); dialog.setCancelable(true); dialog.setContentView(R.layout.extract_file); dialog.getWindow().getAttributes().width = width; DEST = extractDir; final ProgressBar progress = (ProgressBar) dialog.findViewById(R.id.zipProgressBar); final TextView to = (TextView) dialog.findViewById(R.id.zipFileName); final TextView from = (TextView) dialog.findViewById(R.id.zipLoc); final TextView cfile = (TextView) dialog.findViewById(R.id.zipSize); final TextView zsize = (TextView) dialog.findViewById(R.id.zipNoOfFiles); final TextView status = (TextView) dialog.findViewById(R.id.zipFileLocation); if (extractDir == null) to.setText(ctx.getString(R.string.extractingto) + " Cache directory"); else to.setText(ctx.getString(R.string.extractingto) + " " + DEST); from.setText(ctx.getString(R.string.extractingfrom) + " " + file.getName()); if (mode == 2) { //TAR ENTRY HAS TO BE SHARED VIA BLUETOOTH,ETC... TextView t = null;//= (TextView)dialog.findViewById(R.id.preparing); t.setText(ctx.getString(R.string.preparingtoshare)); } try { if (file.getName().endsWith(".tar.gz")) tar = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(file))); else tar = new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(file))); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); tar = null; } final Handler handle = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: progress.setProgress(0); cfile.setText(ctx.getString(R.string.extractingfile) + " " + name); break; case 1: status.setText(name); progress.setProgress((int) prog); break; case 2: try { tar.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (running) { dialog.dismiss(); if (mode == 0) { //after extracting file ,it has to be opened.... new OpenFileDialog(ctx, Uri.parse(dest)); } else if (mode == 2) { //FILE HAS TO BE SHARED.... new BluetoothChooser(ctx, new File(dest).getAbsolutePath(), null); } else { if (errors) Toast.makeText(ctx, ctx.getString(R.string.errorinext), Toast.LENGTH_SHORT).show(); Toast.makeText(ctx, ctx.getString(R.string.fileextracted), Toast.LENGTH_SHORT).show(); } } break; case 3: zsize.setText(size); progress.setMax((int) max); break; case 4: status.setText(ctx.getString(R.string.preparing)); break; case 5: running = false; Toast.makeText(ctx, ctx.getString(R.string.extaborted), Toast.LENGTH_SHORT).show(); } } }; final Thread thread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (running) { if (DEST == null) { DEST = Environment.getExternalStorageDirectory() + "/Android/data/org.anurag.file.quest"; new File(DEST).mkdirs(); } TarArchiveEntry ze; try { while ((ze = tar.getNextTarEntry()) != null) { if (ze.isDirectory()) continue; handle.sendEmptyMessage(4); if (!zFile.isDirectory()) { //EXTRACTING A SINGLE FILE FROM AN ARCHIVE.... if (ze.getName().equalsIgnoreCase(zFile.t_getEntryName())) { try { //SENDING CURRENT FILE NAME.... try { name = zFile.getName(); } catch (Exception e) { name = zFile.t_getEntryName(); } handle.sendEmptyMessage(0); dest = DEST; dest = dest + "/" + name; FileOutputStream out = new FileOutputStream((dest)); max = ze.getSize(); size = AppBackup.size(max, ctx); handle.sendEmptyMessage(3); InputStream fin = tar; while ((read = fin.read(data)) != -1 && running) { out.write(data, 0, read); prog += read; name = AppBackup.status(prog, ctx); handle.sendEmptyMessage(1); } out.flush(); out.close(); fin.close(); break; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); //errors = true; } catch (IOException e) { errors = true; } } } else { //EXTRACTING A DIRECTORY FROM TAR ARCHIVE.... String p = zFile.getPath(); if (p.startsWith("/")) p = p.substring(1, p.length()); if (ze.getName().startsWith(p)) { prog = 0; dest = DEST; name = ze.getName(); String path = name; name = name.substring(name.lastIndexOf("/") + 1, name.length()); handle.sendEmptyMessage(0); String foname = zFile.getPath(); if (!foname.startsWith("/")) foname = "/" + foname; if (!path.startsWith("/")) path = "/" + path; path = path.substring(foname.lastIndexOf("/"), path.lastIndexOf("/")); if (!path.startsWith("/")) path = "/" + path; dest = dest + path; new File(dest).mkdirs(); dest = dest + "/" + name; FileOutputStream out; try { max = ze.getSize(); out = new FileOutputStream((dest)); size = AppBackup.size(max, ctx); handle.sendEmptyMessage(3); // InputStream fin = tar; while ((read = tar.read(data)) != -1 && running) { out.write(data, 0, read); prog += read; name = AppBackup.status(prog, ctx); handle.sendEmptyMessage(1); } out.flush(); out.close(); //fin.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); // errors = true; } catch (IOException e) { errors = true; } catch (Exception e) { //errors = true; } } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); errors = true; } handle.sendEmptyMessage(2); } } }); /* Button cancel = (Button)dialog.findViewById(R.id.calcelButton); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog.dismiss(); handle.sendEmptyMessage(5); } }); Button st = (Button)dialog.findViewById(R.id.extractButton); st.setVisibility(View.GONE);*/ dialog.show(); running = true; thread.start(); dialog.setCancelable(false); progress.setVisibility(View.VISIBLE); }
From source file:net.networksaremadeofstring.cyllell.ViewEnvironments_Fragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { list = (ListView) this.getActivity().findViewById(R.id.environmentsListView); settings = this.getActivity().getSharedPreferences("Cyllell", 0); try {//from w ww . j a v a 2 s . com Cut = new Cuts(getActivity()); } catch (Exception e) { e.printStackTrace(); } dialog = new ProgressDialog(getActivity()); dialog.setTitle("Contacting Chef"); dialog.setMessage("Please wait: Prepping Authentication protocols"); dialog.setIndeterminate(true); if (listOfEnvironments.size() < 1) { dialog.show(); } updateListNotify = new Handler() { public void handleMessage(Message msg) { int tag = msg.getData().getInt("tag", 999999); if (msg.what == 0) { if (tag != 999999) { listOfEnvironments.get(tag).SetSpinnerVisible(); } } else if (msg.what == 1) { //Get rid of the lock CutInProgress = false; //the notifyDataSetChanged() will handle the rest } else if (msg.what == 99) { if (tag != 999999) { Toast.makeText(ViewEnvironments_Fragment.this.getActivity(), "An error occured during that operation.", Toast.LENGTH_LONG).show(); listOfEnvironments.get(tag).SetErrorState(); } } EnvironmentAdapter.notifyDataSetChanged(); } }; final Handler handler = new Handler() { public void handleMessage(Message msg) { //Once we've checked the data is good to use start processing it if (msg.what == 0) { OnClickListener listener = new OnClickListener() { public void onClick(View v) { //Log.i("OnClick","Clicked"); GetMoreDetails((Integer) v.getTag()); } }; OnLongClickListener listenerLong = new OnLongClickListener() { public boolean onLongClick(View v) { selectForCAB((Integer) v.getTag()); return true; } }; EnvironmentAdapter = new EnvironmentListAdaptor(getActivity().getBaseContext(), listOfEnvironments, listener, listenerLong); list = (ListView) getView().findViewById(R.id.environmentsListView); if (list != null) { if (EnvironmentAdapter != null) { list.setAdapter(EnvironmentAdapter); } else { //Log.e("EnvironmentAdapter","EnvironmentAdapter is null"); } } else { //Log.e("List","List is null"); } dialog.dismiss(); } else if (msg.what == 200) { dialog.setMessage("Sending request to Chef..."); } else if (msg.what == 201) { dialog.setMessage("Parsing JSON....."); } else if (msg.what == 202) { dialog.setMessage("Populating UI!"); } else { //Close the Progress dialog dialog.dismiss(); //Alert the user that something went terribly wrong AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create(); alertDialog.setTitle("API Error"); alertDialog.setMessage("There was an error communicating with the API:\n" + msg.getData().getString("exception")); alertDialog.setButton2("Back", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { getActivity().finish(); } }); alertDialog.setIcon(R.drawable.icon); alertDialog.show(); } } }; Thread dataPreload = new Thread() { public void run() { if (listOfEnvironments.size() > 0) { handler.sendEmptyMessage(0); } else { try { handler.sendEmptyMessage(200); Environments = Cut.GetEnvironments(); handler.sendEmptyMessage(201); JSONArray Keys = Environments.names(); for (int i = 0; i < Keys.length(); i++) { listOfEnvironments.add( new Environment(Keys.getString(i), Environments.getString(Keys.getString(i)) .replaceFirst("^(https://|http://).*/environments/", ""))); } handler.sendEmptyMessage(202); handler.sendEmptyMessage(0); } catch (Exception e) { Message msg = new Message(); Bundle data = new Bundle(); data.putString("exception", e.getMessage()); msg.setData(data); msg.what = 1; handler.sendMessage(msg); } } return; } }; dataPreload.start(); return inflater.inflate(R.layout.environments_landing, container, false); }
From source file:cgeo.geocaching.CacheDetailActivity.java
private void resetCoords(final Geocache cache, final Handler handler, final Waypoint wpt, final boolean local, final boolean remote, final ProgressDialog progress) { AndroidRxUtils.networkScheduler.scheduleDirect(new Runnable() { @Override/*from w w w . j a va 2s . co m*/ public void run() { if (local) { runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords)); } }); cache.setCoords(wpt.getCoords()); cache.setUserModifiedCoords(false); cache.deleteWaypointForce(wpt); DataStore.saveUserModifiedCoords(cache); handler.sendEmptyMessage(HandlerResetCoordinates.LOCAL); } final IConnector con = ConnectorFactory.getConnector(cache); if (remote && con.supportsOwnCoordinates()) { runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage( res.getString(R.string.waypoint_coordinates_being_reset_on_website)); } }); final boolean result = con.deleteModifiedCoordinates(cache); runOnUiThread(new Runnable() { @Override public void run() { if (result) { showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website)); } else { showToast(getString(R.string.waypoint_coordinates_upload_error)); } handler.sendEmptyMessage(HandlerResetCoordinates.ON_WEBSITE); notifyDataSetChanged(); } }); } } }); }
From source file:net.networksaremadeofstring.pulsant.portal.ManagedServerLanding.java
public void onCreate(Bundle savedInstanceState) { API.SessionID = getIntent().getStringExtra("sessionid"); super.onCreate(savedInstanceState); setContentView(R.layout.managedserverlanding); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Managed Servers"); //temp//from w w w .ja v a 2 s. co m list = (ListView) findViewById(R.id.ManagedServerList); final ProgressDialog dialog = ProgressDialog.show(this, "Pulsant Portal", "Please wait: loading data....", true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (Success.equals("true")) { UpdateErrorMessage(ErrorMessage); ManagedServerAdaptor adapter = new ManagedServerAdaptor(ManagedServerLanding.this, listOfManagedServers, API.SessionID); list.setAdapter(adapter); /*list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); list.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View view) { if (mActionMode != null) { Log.i("onLongClick","Nuhuh"); return false; } // Start the CAB using the ActionMode.Callback defined above mActionMode = startActionMode(mActionModeCallback); view.setSelected(true); return true; } });*/ } else { UpdateErrorMessage(ErrorMessage); } } }; Thread dataPreload = new Thread() { int ServerCount = 0; public void run() { try { Servers = API.PortalQuery("servers", "none"); Success = Servers.getString("success"); } catch (JSONException e) { //UpdateErrorMessage("An unrecoverable JSON Exception occured."); ErrorMessage = "An unrecoverable JSON Exception occured."; } if (Success.equals("false")) { try { //UpdateErrorMessage(Servers.getString("msg")); ErrorMessage = Servers.getString("msg"); } catch (JSONException e) { //UpdateErrorMessage("An unrecoverable JSON Exception occured."); ErrorMessage = "An unrecoverable JSON Exception occured."; } } else { Log.i("APIFuncs", Servers.toString()); try { ManagedServers = Servers.getJSONArray("servers"); //UpdateErrorMessage(""); ErrorMessage = ""; } catch (JSONException e) { //UpdateErrorMessage("There are no Managed servers in your account."); ErrorMessage = "There are no Managed servers in your account."; } try { ServerCount = ManagedServers.length(); } catch (Exception e) { ServerCount = 0; } if (ServerCount == 0) { ErrorMessage = "There are no Managed servers for your account."; handler.sendEmptyMessage(0); return; } for (int i = 0; i < ServerCount; i++) { try { CurrentServer = ManagedServers.getJSONObject(i).getJSONObject("Server"); } catch (JSONException e1) { Log.e("APIFuncs", e1.getMessage()); } //Log.e("APIFuncs",CurrentServer.toString(3)); listOfManagedServers.add(new ManagedServer(GetString("ip"), GetString("servercode"), GetString("description"), GetString("facility"), GetInt("bandwidth"), GetString("bandwidthTotal"), GetBool("monitored"), GetInt("transferlimit"), GetString("software"), GetString("state"), GetBool("managedbackupenabled"))); } } handler.sendEmptyMessage(0); } }; dataPreload.start(); }
From source file:eu.dirtyharry.androidopsiadmin.Main.java
public void getOPSIDepots() { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), getString(R.string.pd_getdepots), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss();/*from w w w .j av a 2 s . c o m*/ if (GlobalVar.getInstance().getError().equals("null")) { if (doit.equals("true")) { JSONArray result = new JSONArray(); try { result = opsiresult.getJSONArray("result"); depots = new String[result.length()]; for (int i = 0; i < result.length(); i++) { depots[i] = result.getString(i); } } catch (JSONException e) { e.printStackTrace(); } AlertDialog.Builder builder = new AlertDialog.Builder(Main.this); builder.setTitle(getString(R.string.gen_choose)); builder.setSingleChoiceItems(depots, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { dialog.dismiss(); String depot = depots[item]; choosendepot = depot; getOPSIDepotConfig(depot); } }); AlertDialog alert = builder.create(); alert.show(); } else if (doit.equals("serverdown")) { Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip), // serverip + " " // + getString(R.string.to_servernotrechable), Toast.LENGTH_LONG).show(); } } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); JSONArray JSONparams = new JSONArray(); if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) { opsiresult = new JSONObject(); opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip, serverport, "getDepotIds_list", JSONparams, serverusername, serverpasswd); doit = "true"; } else { doit = "serverdown"; // } handler.sendEmptyMessage(0); } }; checkUpdate.start(); }
From source file:com.example.zf_android.trade.ApplyDetailActivity.java
@Override protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) return;/*from ww w. j a va 2 s . c o m*/ switch (requestCode) { case REQUEST_CHOOSE_MERCHANT: { mAgentId = mMerchantId = data.getIntExtra(AGENT_ID, 0); mAgentName = data.getStringExtra(AGENT_NAME); setItemValue(mMerchantKeys[0], mAgentName); getAgentInfo(); break; } case REQUEST_CHOOSE_BANK: { mBankName = data.getStringExtra("bank_name"); mBankNo = data.getStringExtra("bank_no"); setItemValue(customTag, mBankName); setItemValue(mBankKeys[0], mBankName); //FIXME no // setItemValue(mBankKeys[1], mBankNo); break; } case REQUEST_CHOOSE_CITY: { mMerchantProvince = (Province) data.getSerializableExtra(SELECTED_PROVINCE); mMerchantCity = (City) data.getSerializableExtra(SELECTED_CITY); mCityId = mMerchantCity.getId(); setItemValue(mMerchantKeys[8], mMerchantCity.getName()); break; } case REQUEST_CHOOSE_CHANNEL: { mChannelId = data.getIntExtra("channelId", 0); mBillingId = data.getIntExtra("billId", 0); String channelName = data.getStringExtra("channelName"); String billName = data.getStringExtra("billName"); setItemValue(getString(R.string.apply_detail_channel), channelName + " " + billName); break; } case REQUEST_UPLOAD_IMAGE: case REQUEST_TAKE_PHOTO: { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { // CommonUtil.toastShort(ApplyDetailActivity.this, (String) msg.obj); if (null != uploadingTextView) { final String url = (String) msg.obj; LinearLayout item = (LinearLayout) uploadingTextView.getParent().getParent(); updateCustomerDetails(item.getTag(), url); uploadingTextView.setVisibility(View.GONE); ImageView iv_view = (ImageView) item.findViewById(R.id.apply_detail_view); iv_view.setVisibility(View.VISIBLE); iv_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class); i.putExtra("url", url); i.putExtra("justviewer", true); startActivity(i); } }); } } else { CommonUtil.toastShort(ApplyDetailActivity.this, getString(R.string.toast_upload_failed)); if (null != uploadingTextView) { uploadingTextView.setText(getString(R.string.apply_upload_again)); uploadingTextView.setClickable(true); } } } }; if (null != uploadingTextView) { uploadingTextView.setText(getString(R.string.apply_uploading)); uploadingTextView.setClickable(false); } new Thread() { @Override public void run() { String realPath = ""; if (requestCode == REQUEST_TAKE_PHOTO) { realPath = photoPath; } else { Uri uri = data.getData(); if (uri != null) { realPath = getRealPathFromURI(uri); } } if (TextUtils.isEmpty(realPath)) { handler.sendEmptyMessage(0); return; } CommonUtil.uploadFile(realPath, "img", new CommonUtil.OnUploadListener() { @Override public void onSuccess(String result) { try { JSONObject jo = new JSONObject(result); String url = jo.getString("result"); Message msg = new Message(); msg.what = 1; msg.obj = url; handler.sendMessage(msg); } catch (JSONException e) { handler.sendEmptyMessage(0); } } @Override public void onFailed(String message) { handler.sendEmptyMessage(0); } }); } }.start(); break; } } }
From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java
/** * This method sends HTTP request to add order. * * @param user// ww w .j a v a 2s . com * @param handler * @param orderInfo * @return */ public static String sendAddOrderRequest(User user, Handler handler, TableReservationInfo orderInfo) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 15000); HttpConnectionParams.setSoTimeout(httpParameters, 15000); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(ADD_ORDER_URL); Log.e(TAG, "ADD_ORDER_URL = " + ADD_ORDER_URL); MultipartEntity multipartEntity = new MultipartEntity(); // user details String userType = null; String orderUUID = null; try { if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) { userType = "facebook"; multipartEntity.addPart("order_customer_name", new StringBody( user.getUserFirstName() + " " + user.getUserLastName(), Charset.forName("UTF-8"))); } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) { userType = "twitter"; multipartEntity.addPart("order_customer_name", new StringBody(user.getUserName(), Charset.forName("UTF-8"))); } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) { userType = "ibuildapp"; multipartEntity.addPart("order_customer_name", new StringBody(user.getUserName(), Charset.forName("UTF-8"))); } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) { userType = "guest"; multipartEntity.addPart("order_customer_name", new StringBody("Guest", Charset.forName("UTF-8"))); } multipartEntity.addPart("user_type", new StringBody(userType, Charset.forName("UTF-8"))); multipartEntity.addPart("user_id", new StringBody(user.getAccountId(), Charset.forName("UTF-8"))); multipartEntity.addPart("app_id", new StringBody(orderInfo.getAppid(), Charset.forName("UTF-8"))); multipartEntity.addPart("module_id", new StringBody(orderInfo.getModuleid(), Charset.forName("UTF-8"))); // order UUID orderUUID = UUID.randomUUID().toString(); multipartEntity.addPart("order_uid", new StringBody(orderUUID, Charset.forName("UTF-8"))); // order details Date tempDate = orderInfo.getOrderDate(); tempDate.setHours(orderInfo.getOrderTime().houres); tempDate.setMinutes(orderInfo.getOrderTime().minutes); tempDate.getTimezoneOffset(); String timeZone = timeZoneToString(); multipartEntity.addPart("time_zone", new StringBody(timeZone, Charset.forName("UTF-8"))); multipartEntity.addPart("order_date_time", new StringBody(Long.toString(tempDate.getTime() / 1000), Charset.forName("UTF-8"))); multipartEntity.addPart("order_persons", new StringBody(Integer.toString(orderInfo.getPersonsAmount()), Charset.forName("UTF-8"))); multipartEntity.addPart("order_spec_request", new StringBody(orderInfo.getSpecialRequest(), Charset.forName("UTF-8"))); multipartEntity.addPart("order_customer_phone", new StringBody(orderInfo.getPhoneNumber(), Charset.forName("UTF-8"))); multipartEntity.addPart("order_customer_email", new StringBody(orderInfo.getCustomerEmail(), Charset.forName("UTF-8"))); // add security part multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8"))); multipartEntity.addPart("token", new StringBody(Statics.appToken, Charset.forName("UTF-8"))); } catch (Exception e) { Log.d("", ""); } httppost.setEntity(multipartEntity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { String strResponseSaveGoal = httpclient.execute(httppost, responseHandler); Log.d("sendAddOrderRequest", ""); String res = JSONParser.parseQueryError(strResponseSaveGoal); if (res == null || res.length() == 0) { return orderUUID; } else { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } } catch (ConnectTimeoutException conEx) { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } catch (ClientProtocolException ex) { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } catch (IOException ex) { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } }
From source file:com.example.zf_android.activity.MerchantEdit.java
@Override protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return;// w w w . j a v a 2s . c om } String value = ""; if (data != null) { value = data.getStringExtra("value"); } switch (requestCode) { case TYPE_1: merchantEntity.setTitle(value); tv1.setText(value); break; case TYPE_2: merchantEntity.setLegalPersonName(value); tv2.setText(value); break; case TYPE_3: merchantEntity.setLegalPersonCardId(value); tv3.setText(value); break; case TYPE_4: merchantEntity.setBusinessLicenseNo(value); tv4.setText(value); break; case TYPE_5: merchantEntity.setTaxRegisteredNo(value); tv5.setText(value); break; case TYPE_6: merchantEntity.setOrganizationCodeNo(value); tv6.setText(value); break; case TYPE_7: Province province = (Province) data.getSerializableExtra(Constants.CityIntent.SELECTED_PROVINCE); City city = (City) data.getSerializableExtra(Constants.CityIntent.SELECTED_CITY); if (province == null || city == null) { merchantEntity.setCityId(0); tv7.setText(""); } else { merchantEntity.setCityId(city.getId()); tv7.setText(province.getName() + city.getName()); } break; case TYPE_KHYH: merchantEntity.setAccountBankName(value); tvkhyh.setText(value); break; case TYPE_8: merchantEntity.setBankOpenAccount(value); tv8.setText(value); break; case REQUEST_UPLOAD_IMAGE: case REQUEST_TAKE_PHOTO: { final LinearLayout layout = linearLayout.get(MerchantEdit.this.type); final Handler handler = new Handler() { private int type; @Override public void handleMessage(Message msg) { this.type = MerchantEdit.this.type; if (msg.what == 1) { // CommonUtil.toastShort(MerchantEdit.this, // (String) msg.obj); layout.setClickable(false); layout.findViewById(R.id.imgView).setVisibility(View.VISIBLE); layout.findViewById(R.id.textView).setVisibility(View.GONE); String url = (String) msg.obj; layout.setClickable(true); switch (type) { case TYPE_10: merchantEntity.setCardIdFrontPhotoPath(url); break; case TYPE_11: merchantEntity.setCardIdBackPhotoPath(url); break; case TYPE_12: merchantEntity.setBodyPhotoPath(url); break; case TYPE_13: merchantEntity.setLicenseNoPicPath(url); break; case TYPE_14: merchantEntity.setTaxNoPicPath(url); break; case TYPE_15: merchantEntity.setOrgCodeNoPicPath(url); break; case TYPE_16: merchantEntity.setAccountPicPath(url); break; default: break; } } else { CommonUtil.toastShort(MerchantEdit.this, getString(R.string.toast_upload_failed)); layout.setClickable(true); } } }; if (null != layout) { ImageView imgView = (ImageView) layout.findViewById(R.id.imgView); TextView textView = (TextView) layout.findViewById(R.id.textView); imgView.setVisibility(View.GONE); textView.setVisibility(View.VISIBLE); textView.setText(getString(R.string.apply_uploading)); layout.setClickable(false); } new Thread() { @Override public void run() { String realPath = ""; if (requestCode == REQUEST_TAKE_PHOTO) { realPath = photoPath; } else { Uri uri = data.getData(); if (uri != null) { realPath = Tools.getRealPathFromURI(MerchantEdit.this, uri); } } if (TextUtils.isEmpty(realPath)) { handler.sendEmptyMessage(0); return; } CommonUtil.uploadFile(realPath, "img", new CommonUtil.OnUploadListener() { @Override public void onSuccess(String result) { try { JSONObject jo = new JSONObject(result); String url = jo.getString("result"); Message msg = new Message(); msg.what = 1; msg.obj = url; handler.sendMessage(msg); } catch (JSONException e) { handler.sendEmptyMessage(0); } } @Override public void onFailed(String message) { handler.sendEmptyMessage(0); } }); } }.start(); break; } default: break; } }
From source file:org.anurag.file.quest.TaskerActivity.java
/** * FUNCTION RELOADS THE LIST AFTER CERTAIN TASK..... * @param ITEM// w ww . j av a2 s . c om */ private static void refreshList(final int ITEM) { final Handler handle = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case 1: root.setAdapter(RootAdapter); break; case 2: simple.setAdapter(nSimple); break; case 3: load_FIle_Gallery(fPos); break; case 4: nAppAdapter = new AppAdapter(mContext, R.layout.row_list_1, nList); APP_LIST_VIEW.setAdapter(nAppAdapter); } } }; Thread thread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (ITEM == 1) { sFiles = SFileManager.giveMeFileList(); handle.sendEmptyMessage(2); if (SimpleAdapter.MULTI_SELECT) { SimpleAdapter.thumbselection = new boolean[sFiles.size()]; SimpleAdapter.c = 0; } } else if (ITEM == 2) { nFiles = RFileManager.giveMeFileList(); if (RootAdapter.MULTI_SELECT) { RootAdapter.thumbselection = new boolean[nFiles.size()]; RootAdapter.C = 0; } handle.sendEmptyMessage(1); } else if (ITEM == 0) { handle.sendEmptyMessage(3); } else if (ITEM == 3) handle.sendEmptyMessage(4); } }); thread.start(); }
From source file:org.anurag.file.quest.FileQuestHD.java
/** * this function checks for update for File Quest * and makes a notification to download link * in playstore.... // w ww . ja v a2 s.c o m */ private void update_checker() { // TODO Auto-generated method stub Toast.makeText(FileQuestHD.this, R.string.checking_update, Toast.LENGTH_SHORT).show(); final Handler hand = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub switch (msg.what) { case 1://update available.... { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(FileQuestHD.this); mBuilder.setSmallIcon(R.drawable.file_quest_icon); mBuilder.setContentTitle(getString(R.string.app_name)); mBuilder.setContentText(getString(R.string.update_avail)); mBuilder.setTicker(getString(R.string.update_avail)); Toast.makeText(FileQuestHD.this, R.string.update_avail, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://details?id=org.anurag.file.quest")); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendint = PendingIntent.getActivity(FileQuestHD.this, 900, intent, 0); mBuilder.setContentIntent(pendint); mBuilder.setAutoCancel(true); NotificationManager notimgr = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notimgr.notify(1, mBuilder.build()); } break; case 2://no connectivity.... Toast.makeText(FileQuestHD.this, R.string.nointernet, Toast.LENGTH_SHORT).show(); break; case 3: //failed to check for update.... Toast.makeText(FileQuestHD.this, R.string.failed_to_check_for_update, Toast.LENGTH_SHORT) .show(); } } }; Thread th = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (!info.isConnected()) { hand.sendEmptyMessage(2); return; } Scanner scan = new Scanner( new URL("https://www.dropbox.com/s/x1gp7a6ozdvg81g/FQ_UPDATE.txt?dl=1").openStream()); String update = scan.next(); if (!update.equalsIgnoreCase(getString(R.string.version))) hand.sendEmptyMessage(1); scan.close(); } catch (Exception e) { hand.sendEmptyMessage(3); } } }); th.start(); }