List of usage examples for android.os AsyncTask execute
@MainThread public static void execute(Runnable runnable)
From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java
/** Called when the activity is first created. */ @Override//from w w w. j av a 2 s . c o m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { NetworkConnectionChecker.initialize(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("reachable="); layout.addView(tv); this.textView = tv; Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); { Button btn = new Button(this); btn.setText("disp isReachable"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean isReachable = NetworkConnectionChecker.isReachable(); Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG); toast.show(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("upload http AsyncTask"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(0.0.0.0)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { destHost = InetAddress.getByName("0.0.0.0"); if (null != destHost) { try { if (destHost.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + destHost.toString() + " reachable"); } else { Log.d(TAG, "destHost=" + destHost.toString() + " not reachable"); } } catch (IOException e) { } } } catch (UnknownHostException e) { } Log.d(TAG, "destHost=" + destHost); } }); thread.start(); try { thread.join(1000); } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(www.google.com)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("www.google.com"); if (null == dest) { dest = destHost; } if (null != dest) { final String[] uris = new String[] { "http://www.google.com/", "https://www.google.com/" }; for (final String destURI : uris) { URI uri = null; try { uri = new URI(destURI); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { URL url = null; try { url = uri.toURL(); } catch (MalformedURLException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } URLConnection conn = null; if (null != url) { Log.d(TAG, "openConnection before"); try { conn = url.openConnection(); if (null != conn) { conn.setConnectTimeout(3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { //Log.d( TAG, "got Exception" + e.toString(), e ); } Log.d(TAG, "openConnection after"); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responceCode = -1; try { Log.d(TAG, "getResponceCode before"); responceCode = httpConn.getResponseCode(); Log.d(TAG, "getResponceCode after"); } catch (IOException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } Log.d(TAG, "responceCode=" + responceCode); if (0 < responceCode) { isReachable = true; destHost = dest; } Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); } } } // if uri if (isReachable) { //break; } } // for uris } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { String target = null; { ProxySelector proxySelector = ProxySelector.getDefault(); Log.d(TAG, "proxySelector=" + proxySelector); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { Log.d(TAG, e.toString()); } List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { Log.d(TAG, " proxy=" + proxy); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { final SocketAddress sa = proxy.address(); if (sa instanceof InetSocketAddress) { final InetSocketAddress isa = (InetSocketAddress) sa; target = isa.getHostName(); break; } } } } } } } if (null == target) { target = "kkkon.sakura.ne.jp"; } InetAddress dest = InetAddress.getByName(target); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); { ProxySelector proxySelector = ProxySelector.getDefault(); //Log.d( TAG, "proxySelector=" + proxySelector ); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { //Log.d( TAG, " proxy=" + proxy ); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { URL url = uri.toURL(); URLConnection conn = null; if (null != url) { try { conn = url.openConnection(proxy); if (null != conn) { conn.setConnectTimeout( 3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { Log.d(TAG, "got Exception" + e.toString(), e); } if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; if (0 < httpConn .getResponseCode()) { isReachable = true; } Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); //httpConn.setInstanceFollowRedirects( false ); //httpConn.setRequestMethod( "HEAD" ); //conn.connect(); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); } } } } } } } } } } destHost = dest; } catch (IOException e) { Log.d(TAG, "got Excpetion " + e.toString()); } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } setContentView(layout); }
From source file:org.tanrabad.survey.presenter.PlaceListInDatabaseFragment.java
protected void loadPlaceList() { emptyPlacesView.showProgressBar();// w w w. ja va2 s . c om AsyncTask.execute(new Runnable() { @Override public void run() { if (placeTypeId > 0) placeChooser.getPlaceListWithPlaceTypeFilter(placeTypeId); else placeChooser.getPlaceList(); } }); }
From source file:com.hkm.oc.wv.supportwebview.webviewSupports.java
protected void SavePNG(final int requestCode, final Uri filepath_uri) { final AsyncTask<Integer, Void, Boolean> task = new AsyncTask<Integer, Void, Boolean>() { private String error = ""; // private String imageEncoded = ""; @Override//from w ww . j av a 2 s .c om protected Boolean doInBackground(Integer... k) { boolean result = false; try { Bitmap immagex = null; if (requestCode == WLR_CLIENT_SIGN) current_job_task.saveSignWLRClient(filepath_uri); if (requestCode == WLR_TEAM_SIGN) current_job_task.saveSignWLRTeam(filepath_uri); if (requestCode == WCS_CLIENT_SIGN) current_job_task.saveSignWCSClient(filepath_uri); // immagex = BitmapFactory.decodeStream(mFragmentActivity.getContentResolver().openInputStream(filepath_uri)); immagex = Tool.LoadScaledBitmap(mFragmentActivity.getContentResolver(), filepath_uri, 100000); if (immagex == null) throw new FileNotFoundException(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); //http://stackoverflow.com/questions/22031636/convert-android-base64-bitmap-and-display-on-html-base64-image final String imageEncoded = Base64.encodeToString(b, Base64.NO_WRAP); // final int strFileName = k[0]; // mWebView.loadUrl("javascript:PControl.checkComplete()"); /* final String m = new String(imageEncoded); final StringBuffer strBuilder = new StringBuffer(); final int bufferchars = 200; final int t = (int) Math.ceil(m.length() / bufferchars); for (int i = 0; i < t; i++) { final StringBuilder cc = new StringBuilder(); int next = (i + 1) * bufferchars; int dest = next > m.length() ? m.length() : next; final CharSequence g = m.subSequence(i * bufferchars, dest); cc.append(g); strBuilder.append(g); mWebView.loadUrl("javascript:PControl.fillPNG('" + cc.toString() + "');"); } String TAG = "loading image tag"; Log.d(TAG, strBuilder.toString());*/ result = true; } catch (FileNotFoundException e) { result = false; } catch (Exception e) { result = false; } return result; } @Override protected void onPostExecute(Boolean saved) { runOnUiThread(new Runnable() { @Override public void run() { progressBar_dismiss("signature saved and confirmed.", new DsingleCB() { @Override public void oncontified(DialogFragment dialog) { if (requestCode == WLR_CLIENT_SIGN) mWebView.loadUrl( "javascript:PControl.fillEndF(1,'" + filepath_uri.toString() + "');"); if (requestCode == WLR_TEAM_SIGN) mWebView.loadUrl( "javascript:PControl.fillEndF(2,'" + filepath_uri.toString() + "');"); if (requestCode == WCS_CLIENT_SIGN) mWebView.loadUrl( "javascript:PControl.fillEndF(3,'" + filepath_uri.toString() + "');"); } }); } }); } }; task.execute(requestCode); }
From source file:com.authorwjf.bounce.BluetoothChat.java
private void fetchScoreboardFunc() { // Fetch the scores ... AsyncTask.execute(new Runnable() { public void run() { try { // Instantiate the scoreboardEntriesList //ArrayList<ScoreboardEntry> scoreboardEntriesList = new ArrayList<ScoreboardEntry>(); // Get the attributes used for the HTTP GET //String currentUserFBID = application.getCurrentFBUser().getId(); //String currentUserAccessToken = Session.getActiveSession().getAccessToken(); Random rgen = new Random(); double currentScore = rgen.nextDouble(); String currentUserFBID = Main.fbid; // Execute the HTTP Get to our server for the scores of the user's friends HttpClient client = new DefaultHttpClient(); /* Update this */ //String getURL = "http://www.friendsmash.com/scores?fbid=" + currentUserFBID + "&access_token=" + currentUserAccessToken; String getURL = "http://omnidrive.herokuapp.com/data?fbid=" + currentUserFBID + "¤tScore=" + currentScore;/*from www.j a va2 s. c om*/ //String getURL = "http://www.omnidrive.io/api/?fbid=" + currentUserFBID + "¤tScore=" + mpg; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); } catch (Exception e) { Log.e(BluetoothChat.TAG, e.toString()); } } }); }
From source file:net.robotmedia.acv.ui.widget.OcrLayout.java
/** Start task that will show a progress dialog, copy OCR assets to external storage and prepare for capture. */ private void runCopyAssetsTask() { /** Task responsible for showing a progress dialog and copying the OCR assets to external storage. */ AsyncTask<Void, Void, Void> copyAssetsTask = new AsyncTask<Void, Void, Void>() { final Handler prepareCaptureHandler = new Handler(); /** Runnable that will start the capture process */ final Runnable prepareCaptureRunnable = new Runnable() { public void run() { prepareCapture();/*from ww w.j a va2s . c om*/ } }; @Override protected void onPreExecute() { assetCopyProgressDialog = new ProgressDialog(context); assetCopyProgressDialog.setTitle(getResources().getString(R.string.ocr_load_assets_dialog_title)); assetCopyProgressDialog.setMessage(getResources().getString(R.string.ocr_load_assets_dialog_msg)); assetCopyProgressDialog.setCancelable(false); assetCopyProgressDialog.setIndeterminate(true); assetCopyProgressDialog.show(); } @Override protected Void doInBackground(Void... arg0) { copyOcrAssets(); prepareCaptureHandler.post(prepareCaptureRunnable); return null; } @Override protected void onPostExecute(Void result) { if (assetCopyProgressDialog != null) { assetCopyProgressDialog.dismiss(); } } }; copyAssetsTask.execute((Void[]) null); }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override//from ww w .j a va2 s . c o m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { ExceptionHandler.initialize(context); if (ExceptionHandler.needReport()) { final String fileName = ExceptionHandler.getBugReportFileAbsolutePath(); final File file = new File(fileName); final File fileZip; { String strFileZip = file.getAbsolutePath(); { int index = strFileZip.lastIndexOf('.'); if (0 < index) { strFileZip = strFileZip.substring(0, index); strFileZip += ".zip"; } } Log.d(TAG, strFileZip); fileZip = new File(strFileZip); if (fileZip.exists()) { fileZip.delete(); } } if (file.exists()) { Log.d(TAG, file.getAbsolutePath()); InputStream inStream = null; ZipOutputStream outStream = null; try { inStream = new FileInputStream(file); String strFileName = file.getAbsolutePath(); { int index = strFileName.lastIndexOf(File.separatorChar); if (0 < index) { strFileName = strFileName.substring(index + 1); } } Log.d(TAG, strFileName); outStream = new ZipOutputStream(new FileOutputStream(fileZip)); byte[] buff = new byte[8124]; { ZipEntry entry = new ZipEntry(strFileName); outStream.putNextEntry(entry); int len = 0; while (0 < (len = inStream.read(buff))) { outStream.write(buff, 0, len); } outStream.closeEntry(); } outStream.finish(); outStream.flush(); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != outStream) { try { outStream.close(); } catch (Exception e) { } } outStream = null; if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } Log.i(TAG, "zip created"); } if (file.exists()) { // upload or send e-mail InputStream inStream = null; StringBuilder sb = new StringBuilder(); try { inStream = new FileInputStream(file); byte[] buff = new byte[8124]; int readed = 0; do { readed = inStream.read(buff); for (int i = 0; i < readed; i++) { sb.append((char) buff[i]); } } while (readed >= 0); final String str = sb.toString(); Log.i(TAG, str); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if (null != defaultLocale) { if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) { title = ""; message = "?????????"; positive = "?"; negative = ""; needDefaultLang = false; } } if (needDefaultLang) { title = "ERROR"; message = "Got unexpected error. Do you want to send information of error."; positive = "Send"; negative = "Cancel"; } alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderMailClient.upload(context, file, new String[] { "diverKon+sakura@gmail.com" }); } }); alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip, "http://kkkon.sakura.ne.jp/android/bug"); } }); alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { ExceptionHandler.clearReport(); } }); alertDialog.show(); } // TODO separate activity for crash report //DefaultCheckerAPK.checkAPK( this, null ); } ExceptionHandler.registHandler(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); Button btn2 = new Button(this); btn2.setText("reinstall apk"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); if (fileApk.exists()) { foundApk = true; Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); } } if (false == foundApk) { for (int i = 0; i < 10; ++i) { File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk"); Log.d(TAG, "check apk:" + fileApk.getAbsolutePath()); if (fileApk.exists()) { Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath()); /* * // require parmission { final String strCmd = "pm install -r " + fileApk.getAbsolutePath(); try { Runtime.getRuntime().exec( strCmd ); } catch ( IOException e ) { Log.e( TAG, "got exception", e ); } } */ Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); break; } } } } }); layout.addView(btn2); Button btn3 = new Button(this); btn3.setText("check apk"); btn3.setOnClickListener(new View.OnClickListener() { private boolean checkApk(final File fileApk, final ZipEntryFilter filter) { final boolean[] result = new boolean[1]; result[0] = true; final Thread thread = new Thread(new Runnable() { @Override public void run() { if (fileApk.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(fileApk); List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size()); for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { ZipEntry ent = e.nextElement(); Log.d(TAG, ent.getName()); Log.d(TAG, "" + ent.getSize()); final boolean accept = filter.accept(ent); if (accept) { list.add(ent); } } Log.d(TAG, Build.CPU_ABI); // API 4 Log.d(TAG, Build.CPU_ABI2); // API 8 final String[] abiArray = { Build.CPU_ABI // API 4 , Build.CPU_ABI2 // API 8 }; String abiMatched = null; { boolean foundMatched = false; for (final String abi : abiArray) { if (null == abi) { continue; } if (0 == abi.length()) { continue; } for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abi + "/"; if (entry.getName().startsWith(prefixABI)) { abiMatched = abi; foundMatched = true; break; } } if (foundMatched) { break; } } } Log.d(TAG, "matchedAbi=" + abiMatched); if (null != abiMatched) { boolean needReInstall = false; for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abiMatched + "/"; if (entry.getName().startsWith(prefixABI)) { final String jniName = entry.getName().substring(prefixABI.length()); Log.d(TAG, "jni=" + jniName); final String strFileDst = context.getApplicationInfo().nativeLibraryDir + "/" + jniName; Log.d(TAG, strFileDst); final File fileDst = new File(strFileDst); if (!fileDst.exists()) { Log.w(TAG, "needReInstall: content missing " + strFileDst); needReInstall = true; } else { assert (entry.getSize() <= Integer.MAX_VALUE); if (fileDst.length() != entry.getSize()) { Log.w(TAG, "needReInstall: size broken " + strFileDst); needReInstall = true; } else { //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) ); final int size = (int) entry.getSize(); byte[] buffSrc = new byte[size]; { InputStream inStream = null; try { inStream = zipFile.getInputStream(entry); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffSrc, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } byte[] buffDst = new byte[(int) fileDst.length()]; { InputStream inStream = null; try { inStream = new FileInputStream(fileDst); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffDst, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } if (Arrays.equals(buffSrc, buffDst)) { Log.d(TAG, " content equal " + strFileDst); // OK } else { Log.w(TAG, "needReInstall: content broken " + strFileDst); needReInstall = true; } } } } } // for ZipEntry if (needReInstall) { // need call INSTALL APK Log.w(TAG, "needReInstall apk"); result[0] = false; } else { Log.d(TAG, "no need ReInstall apk"); } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != zipFile) { try { zipFile.close(); } catch (Exception e) { } } } } } }); thread.setName("check jni so"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now checking installation. Cancel check?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ try { thread.join(); } catch (InterruptedException e) { Log.d(TAG, "got exception", e); } return result[0]; } @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); this.checkApk(fileApk, new ZipEntryFilter() { @Override public boolean accept(ZipEntry entry) { if (entry.isDirectory()) { return false; } final String filename = entry.getName(); if (filename.startsWith("lib/")) { return true; } return false; } }); } } }); layout.addView(btn3); Button btn4 = new Button(this); btn4.setText("print dir and path"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { { final File file = context.getCacheDir(); Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile()); } { final File file = context.getExternalCacheDir(); // API 8 if (null == file) { // no permission Log.d(TAG, "Ctx.ExternalCacheDir="); } else { Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath()); } } { final File file = context.getFilesDir(); Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath()); } { final String value = context.getPackageResourcePath(); Log.d(TAG, "Ctx.PackageResourcePath=" + value); } { final String[] files = context.fileList(); if (null == files) { Log.d(TAG, "Ctx.fileList=" + files); } else { for (final String filename : files) { Log.d(TAG, "Ctx.fileList=" + filename); } } } { final File file = Environment.getDataDirectory(); Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getDownloadCacheDirectory(); Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getExternalStorageDirectory(); Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getRootDirectory(); Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath()); } { final ApplicationInfo appInfo = context.getApplicationInfo(); Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir); Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9 Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir); { final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles; if (null == sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles); } else { for (final String fileName : sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName); } } } Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir); } { Log.d(TAG, "System.Properties start"); final Properties properties = System.getProperties(); if (null != properties) { for (final Object key : properties.keySet()) { String value = properties.getProperty((String) key); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.Properties end"); } { Log.d(TAG, "System.getenv start"); final Map<String, String> mapEnv = System.getenv(); if (null != mapEnv) { for (final Map.Entry<String, String> entry : mapEnv.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.getenv end"); } } }); layout.addView(btn4); Button btn5 = new Button(this); btn5.setText("check INSTALL_NON_MARKET_APPS"); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SettingsCompat.initialize(context); if (SettingsCompat.isAllowedNonMarketApps()) { Log.d(TAG, "isAllowdNonMarketApps=true"); } else { Log.d(TAG, "isAllowdNonMarketApps=false"); } } }); layout.addView(btn5); Button btn6 = new Button(this); btn6.setText("send email"); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mailto = new Intent(); mailto.setAction(Intent.ACTION_SENDTO); mailto.setType("message/rfc822"); mailto.setData(Uri.parse("mailto:")); mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" }); mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName()); mailto.putExtra(Intent.EXTRA_TEXT, "body text"); //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); //context.startActivity( mailto ); Intent intent = Intent.createChooser(mailto, "Send Email"); if (null != intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { Log.d(TAG, "got Exception", e); } } } }); layout.addView(btn6); Button btn7 = new Button(this); btn7.setText("upload http thread"); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "brd=" + Build.BRAND); Log.d(TAG, "prd=" + Build.PRODUCT); //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); final Thread thread = new Thread(new Runnable() { @Override public void run() { Log.d(TAG, "upload thread tid=" + android.os.Process.myTid()); try { HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug"); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); } Log.d(TAG, "upload finish"); } }); thread.setName("upload crash"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now uploading error information. Cancel upload?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ /* try { thread.join(); // must call. leak handle... } catch ( InterruptedException e ) { Log.d( TAG, "got Exception", e ); } */ } }); layout.addView(btn7); Button btn8 = new Button(this); btn8.setText("upload http AsyncTask"); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn8); Button btn9 = new Button(this); btn9.setText("call checkAPK"); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null); Log.i(TAG, "checkAPK result=" + result); } }); layout.addView(btn9); setContentView(layout); }
From source file:com.microsoft.projectoxford.face.samples.ui.Camera2BasicFragment.java
private void detectAndFrame() { final Bitmap bm = BitmapFactory .decodeFile(getActivity().getExternalFilesDir(null).getAbsolutePath() + "/pic.jpg"); final Bitmap bitm = Bitmap.createScaledBitmap(bm, bm.getWidth() / 8, bm.getHeight() / 8, true); final Bitmap bn = BitmapFactory .decodeFile(getActivity().getExternalFilesDir(null).getAbsolutePath() + "/pic_l.jpg"); final Bitmap bitn = Bitmap.createScaledBitmap(bn, bn.getWidth() / 8, bn.getHeight() / 8, true); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitm.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); final AsyncTask<UUID, String, IdentifyResult[]> identifyTask = new AsyncTask<UUID, String, IdentifyResult[]>() { private boolean mSucceed = true; private String mPersonGroupId = getString(R.string.group_id); @Override//w w w . ja v a2 s . c o m protected IdentifyResult[] doInBackground(UUID... params) { try { // Start identification. return faceServiceClient.identity(this.mPersonGroupId, /* personGroupId */ params, /* faceIds */ 1); /* maxNumOfCandidatesReturned */ } catch (Exception e) { mSucceed = false; return null; } } @Override protected void onPostExecute(IdentifyResult[] result) { // Show the result on screen when detection is done. if (result == null) { showToast("error"); return; } if (result[0].candidates.size() > 0) { showToast("pass"); plu.unlock(); } else { showToast("no such user"); } } }; AsyncTask<InputStream, String, Face[]> detectTask = new AsyncTask<InputStream, String, Face[]>() { @Override protected Face[] doInBackground(InputStream... params) { try { publishProgress("Detecting..."); result = faceServiceClient.detect(params[0], true, // returnFaceId true, // returnFaceLandmarks null // returnFaceAttributes: a string like "age, gender" ); if (result == null) { publishProgress("Detection Finished. Nothing detected"); return null; } publishProgress(String.format("Detection Finished. %d face(s) detected", result.length)); return result; } catch (Exception e) { publishProgress("Detection failed"); return null; } } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(String... progress) { } @Override protected void onPostExecute(Face[] result) { if (result == null || result.length == 0) { showToast("No Face"); return; } if (result.length > 1) { showToast("More than one Face"); return; } if (checkb(bitm, bitn) && checkl(bitm, bitn, result[0].faceLandmarks.eyeLeftOuter.x, result[0].faceLandmarks.eyeLeftTop.y, result[0].faceLandmarks.eyeLeftInner.x, result[0].faceLandmarks.eyeLeftBottom.y) && checkl(bitm, bitn, result[0].faceLandmarks.eyeRightInner.x, result[0].faceLandmarks.eyeRightTop.y, result[0].faceLandmarks.eyeRightOuter.x, result[0].faceLandmarks.eyeRightBottom.y)) { List<UUID> faceIds = new ArrayList<>(); for (Face face : result) { faceIds.add(face.faceId); } identifyTask.execute(faceIds.toArray(new UUID[faceIds.size()])); //showToast("Human"); } else { showToast("Photo"); try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } } } }; detectTask.execute(inputStream); }
From source file:com.facebook.android.friendsmash.ScoreboardFragment.java
private void fetchScoreboardEntries() { // Fetch the scores ... AsyncTask.execute(new Runnable() { public void run() { try { // Instantiate the scoreboardEntriesList ArrayList<ScoreboardEntry> scoreboardEntriesList = new ArrayList<ScoreboardEntry>(); // Get the attributes used for the HTTP GET String currentUserFBID = application.getCurrentFBUser().getId(); String currentUserAccessToken = Session.getActiveSession().getAccessToken(); // Execute the HTTP Get to our server for the scores of the user's friends HttpClient client = new DefaultHttpClient(); String getURL = "http://www.friendsmash.com/scores?fbid=" + currentUserFBID + "&access_token=" + currentUserAccessToken; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); // Parse the response HttpEntity responseEntity = responseGet.getEntity(); String response = EntityUtils.toString(responseEntity); if (!response.equals(null)) { JSONArray responseJSONArray = new JSONArray(response); // Go through the response JSON Array to populate the scoreboard if (responseJSONArray != null && responseJSONArray.length() > 0) { // Loop through all users that have been retrieved for (int i = 0; i < responseJSONArray.length(); i++) { // Store the user details in the following attributes String userID = null; String userName = null; int userScore = -1; // Extract the user information JSONObject currentUser = responseJSONArray.optJSONObject(i); if (currentUser != null) { userID = currentUser.optString("fbid"); userName = currentUser.optString("first_name"); String fetchedScoreAsString = currentUser.optString("highscore"); if (fetchedScoreAsString != null) { userScore = Integer.parseInt(fetchedScoreAsString); }/*from ww w . ja v a2 s .co m*/ if (userID != null && userName != null && userScore >= 0) { // All attributes have been successfully fetched, so create a new // ScoreboardEntry and add it to the List ScoreboardEntry currentUserScoreboardEntry = new ScoreboardEntry(userID, userName, userScore); scoreboardEntriesList.add(currentUserScoreboardEntry); } } } } } // Now that all scores should have been fetched and added to the scoreboardEntriesList, sort it, // set it within scoreboardFragment and then callback to scoreboardFragment to populate the scoreboard Comparator<ScoreboardEntry> comparator = Collections.reverseOrder(); Collections.sort(scoreboardEntriesList, comparator); application.setScoreboardEntriesList(scoreboardEntriesList); // Populate the scoreboard on the UI thread uiHandler.post(new Runnable() { @Override public void run() { populateScoreboard(); } }); } catch (Exception e) { Log.e(FriendSmashApplication.TAG, e.toString()); closeAndShowError(getResources().getString(R.string.network_error)); } } }); }
From source file:org.sufficientlysecure.keychain.ui.keyview.ViewKeyActivity.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { /* TODO better error handling? May cause problems when a key is deleted, * because the notification triggers faster than the activity closes. *//*from w w w.ja va 2 s . c o m*/ // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) switch (loader.getId()) { case LOADER_ID_UNIFIED: { // Avoid NullPointerExceptions... if (data.getCount() == 0) { return; } if (data.moveToFirst()) { // get name, email, and comment from USER_ID String name = data.getString(INDEX_NAME); mCollapsingToolbarLayout.setTitle(name != null ? name : getString(R.string.user_id_no_name)); mMasterKeyId = data.getLong(INDEX_MASTER_KEY_ID); mFingerprint = data.getBlob(INDEX_FINGERPRINT); mIsSecret = data.getInt(INDEX_HAS_ANY_SECRET) != 0; mHasEncrypt = data.getInt(INDEX_HAS_ENCRYPT) != 0; mIsRevoked = data.getInt(INDEX_IS_REVOKED) > 0; mIsExpired = data.getInt(INDEX_IS_EXPIRED) != 0; mIsSecure = data.getInt(INDEX_IS_SECURE) == 1; mIsVerified = data.getInt(INDEX_VERIFIED) > 0; // queue showing of the main fragment showMainFragment(); // if the refresh animation isn't playing if (!mRotate.hasStarted() && !mRotateSpin.hasStarted()) { // re-create options menu based on mIsSecret, mIsVerified supportInvalidateOptionsMenu(); // this is done at the end of the animation otherwise } AsyncTask<Long, Void, Bitmap> photoTask = new AsyncTask<Long, Void, Bitmap>() { protected Bitmap doInBackground(Long... mMasterKeyId) { return new ContactHelper(ViewKeyActivity.this).loadPhotoByMasterKeyId(mMasterKeyId[0], true); } protected void onPostExecute(Bitmap photo) { if (photo == null) { return; } mPhoto.setImageBitmap(photo); mPhoto.setColorFilter(getResources().getColor(R.color.toolbar_photo_tint), PorterDuff.Mode.SRC_ATOP); mPhotoLayout.setVisibility(View.VISIBLE); } }; boolean showStatusText = mIsSecure && !mIsExpired && !mIsRevoked; if (showStatusText) { mStatusText.setVisibility(View.VISIBLE); if (mIsSecret) { mStatusText.setText(R.string.view_key_my_key); } else if (mIsVerified) { mStatusText.setText(R.string.view_key_verified); } else { mStatusText.setText(R.string.view_key_unverified); } } else { mStatusText.setVisibility(View.GONE); } // Note: order is important int color; if (mIsRevoked) { mStatusImage.setVisibility(View.VISIBLE); KeyFormattingUtils.setStatusImage(this, mStatusImage, mStatusText, State.REVOKED, R.color.icons, true); // noinspection deprecation, fix requires api level 23 color = getResources().getColor(R.color.key_flag_red); mActionEncryptFile.setVisibility(View.INVISIBLE); mActionEncryptText.setVisibility(View.INVISIBLE); hideFab(); mQrCodeLayout.setVisibility(View.GONE); } else if (!mIsSecure) { mStatusImage.setVisibility(View.VISIBLE); KeyFormattingUtils.setStatusImage(this, mStatusImage, mStatusText, State.INSECURE, R.color.icons, true); // noinspection deprecation, fix requires api level 23 color = getResources().getColor(R.color.key_flag_red); mActionEncryptFile.setVisibility(View.INVISIBLE); mActionEncryptText.setVisibility(View.INVISIBLE); hideFab(); mQrCodeLayout.setVisibility(View.GONE); } else if (mIsExpired) { mStatusImage.setVisibility(View.VISIBLE); KeyFormattingUtils.setStatusImage(this, mStatusImage, mStatusText, State.EXPIRED, R.color.icons, true); // noinspection deprecation, fix requires api level 23 color = getResources().getColor(R.color.key_flag_red); mActionEncryptFile.setVisibility(View.INVISIBLE); mActionEncryptText.setVisibility(View.INVISIBLE); hideFab(); mQrCodeLayout.setVisibility(View.GONE); } else if (mIsSecret) { mStatusImage.setVisibility(View.GONE); // noinspection deprecation, fix requires api level 23 color = getResources().getColor(R.color.key_flag_green); // reload qr code only if the fingerprint changed if (!Arrays.equals(mFingerprint, mQrCodeLoaded)) { loadQrCode(mFingerprint); } photoTask.execute(mMasterKeyId); mQrCodeLayout.setVisibility(View.VISIBLE); // and place leftOf qr code // RelativeLayout.LayoutParams nameParams = (RelativeLayout.LayoutParams) // mName.getLayoutParams(); // // remove right margin // nameParams.setMargins(FormattingUtils.dpToPx(this, 48), 0, 0, 0); // if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // nameParams.setMarginEnd(0); // } // nameParams.addRule(RelativeLayout.LEFT_OF, R.id.view_key_qr_code_layout); // mName.setLayoutParams(nameParams); RelativeLayout.LayoutParams statusParams = (RelativeLayout.LayoutParams) mStatusText .getLayoutParams(); statusParams.setMargins(FormattingUtils.dpToPx(this, 48), 0, 0, 0); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { statusParams.setMarginEnd(0); } statusParams.addRule(RelativeLayout.LEFT_OF, R.id.view_key_qr_code_layout); mStatusText.setLayoutParams(statusParams); mActionEncryptFile.setVisibility(View.VISIBLE); mActionEncryptText.setVisibility(View.VISIBLE); showFab(); // noinspection deprecation (no getDrawable with theme at current minApi level 15!) mFab.setImageDrawable(getResources().getDrawable(R.drawable.ic_repeat_white_24dp)); } else { mActionEncryptFile.setVisibility(View.VISIBLE); mActionEncryptText.setVisibility(View.VISIBLE); mQrCodeLayout.setVisibility(View.GONE); if (mIsVerified) { mStatusText.setText(R.string.view_key_verified); mStatusImage.setVisibility(View.VISIBLE); KeyFormattingUtils.setStatusImage(this, mStatusImage, mStatusText, State.VERIFIED, R.color.icons, true); // noinspection deprecation, fix requires api level 23 color = getResources().getColor(R.color.key_flag_green); photoTask.execute(mMasterKeyId); hideFab(); } else { mStatusText.setText(R.string.view_key_unverified); mStatusImage.setVisibility(View.VISIBLE); KeyFormattingUtils.setStatusImage(this, mStatusImage, mStatusText, State.UNVERIFIED, R.color.icons, true); // noinspection deprecation, fix requires api level 23 color = getResources().getColor(R.color.key_flag_orange); showFab(); } } if (mPreviousColor == 0 || mPreviousColor == color) { mAppBarLayout.setBackgroundColor(color); mCollapsingToolbarLayout.setContentScrimColor(color); mCollapsingToolbarLayout.setStatusBarScrimColor(getStatusBarBackgroundColor(color)); mPreviousColor = color; } else { ObjectAnimator colorFade = ObjectAnimator.ofObject(mAppBarLayout, "backgroundColor", new ArgbEvaluator(), mPreviousColor, color); mCollapsingToolbarLayout.setContentScrimColor(color); mCollapsingToolbarLayout.setStatusBarScrimColor(getStatusBarBackgroundColor(color)); colorFade.setDuration(1200); colorFade.start(); mPreviousColor = color; } //noinspection deprecation mStatusImage.setAlpha(80); break; } } } }
From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java
/** * Export data./*from w ww. j a v a 2s . co m*/ * * @param descr * description of the exported rule set * @param fn * one of the predefined file names from {@link DataProvider}. */ private void exportData(final String descr, final String fn) { if (descr == null) { final EditText et = new EditText(this); Builder builder = new Builder(this); builder.setView(et); builder.setCancelable(true); builder.setTitle(R.string.export_rules_descr); builder.setNegativeButton(android.R.string.cancel, null); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { Preferences.this.exportData(et.getText().toString(), fn); } }); builder.show(); } else { final ProgressDialog d = new ProgressDialog(this); d.setIndeterminate(true); d.setMessage(this.getString(R.string.export_progr)); d.setCancelable(false); d.show(); // run task in background final AsyncTask<Void, Void, String> task = // . new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(final Void... params) { if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) { return DataProvider.backupRuleSet(Preferences.this, descr); } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) { return DataProvider.backupLogs(Preferences.this, descr); } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) { return DataProvider.backupNumGroups(Preferences.this, descr); } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) { return DataProvider.backupHourGroups(Preferences.this, descr); } return null; } @Override protected void onPostExecute(final String result) { Log.d(TAG, "export:\n" + result); System.out.println("\n" + result); d.dismiss(); if (result != null && result.length() > 0) { Uri uri = null; int resChooser = -1; if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) { uri = DataProvider.EXPORT_RULESET_URI; resChooser = R.string.export_rules_; } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) { uri = DataProvider.EXPORT_LOGS_URI; resChooser = R.string.export_logs_; } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) { uri = DataProvider.EXPORT_NUMGROUPS_URI; resChooser = R.string.export_numgroups_; } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) { uri = DataProvider.EXPORT_HOURGROUPS_URI; resChooser = R.string.export_hourgroups_; } final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(DataProvider.EXPORT_MIMETYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(Intent.EXTRA_SUBJECT, // . "Call Meter 3G export"); intent.addCategory(Intent.CATEGORY_DEFAULT); try { final File d = Environment.getExternalStorageDirectory(); final File f = new File(d, DataProvider.PACKAGE + File.separator + fn); f.mkdirs(); if (f.exists()) { f.delete(); } f.createNewFile(); FileWriter fw = new FileWriter(f); fw.append(result); fw.close(); // call an exporting app with the uri to the // preferences Preferences.this.startActivity( Intent.createChooser(intent, Preferences.this.getString(resChooser))); } catch (IOException e) { Log.e(TAG, "error writing export file", e); Toast.makeText(Preferences.this, R.string.err_export_write, Toast.LENGTH_LONG) .show(); } } } }; task.execute((Void) null); } }