List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:export.UploadManager.java
void syncFeed(final Uploader uploader) { if (uploader == null) { nextSyncFeed();/* www.j av a 2s.com*/ return; } final FeedList.FeedUpdater feedUpdater = feedList.getUpdater(); feedUpdater.start(uploader.getName()); new AsyncTask<Uploader, String, Uploader.Status>() { @Override protected Uploader.Status doInBackground(Uploader... params) { try { return params[0].getFeed(feedUpdater); } catch (Exception ex) { ex.printStackTrace(); return Uploader.Status.ERROR; } } @Override protected void onPostExecute(Uploader.Status result) { if (result == Uploader.Status.OK) { feedUpdater.complete(); } else if (result == Uploader.Status.NEED_AUTH) { handleAuth(new Callback() { @Override public void run(String uploaderName, Uploader.Status s2) { if (s2 == Uploader.Status.OK) { syncFeed(uploader); } else { nextSyncFeed(); } } }, uploader, result.authMethod); return; } else { if (result.ex != null) result.ex.printStackTrace(); } nextSyncFeed(); } }.execute(uploader); }
From source file:dev.memento.MainActivity.java
/** * Find all mementos for the current URL, then display them to the user so one * can be chosen./* ww w .j a v a2s . c om*/ */ private void findMementos() { mFindMementos = new AsyncTask<Void, Void, Void>() { private ProgressDialog pd; @Override protected void onPreExecute() { pd = new ProgressDialog(MainActivity.this); pd.setTitle("Fetching Mementos..."); pd.setMessage("Please wait."); pd.setCancelable(true); pd.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { // Get rid of dialog box but allow fetching to continue mFindMementos.cancel(false); } }); pd.setIndeterminate(true); pd.show(); } @Override protected Void doInBackground(Void... arg0) { // Just in case an archive URL was being viewed mOriginalUrl = Utilities.getUrlFromArchiveUrl(mOriginalUrl); // Load the Timemap directly. I'm hard-coded the timemap URLs for // which unfortunately may need to be changed over time. String timemapUrl = "http://mementoproxy.lanl.gov/aggr/timemap/link/1/"; if (mDefaultTimegateUri.startsWith("http://mementoproxy.cs.odu")) timemapUrl = "http://mementoproxy.cs.odu.edu/aggr/timemap/link/"; timemapUrl = "<" + timemapUrl + mOriginalUrl + ">;rel=\"timemap\";type=\"application/link-format\""; Link link = new Link(timemapUrl); mTimeMaps.clear(); mTimeMaps.add(new TimeMap(link)); if (!accessTimeMap() && mErrorMessage == null) mErrorMessage = "There were problems accessing the Memento's TimeMap. " + "Please try again later."; return null; } @Override protected void onPostExecute(Void result) { pd.dismiss(); if (mErrorMessage != null) displayError(mErrorMessage.toString()); else if (mMementos.size() == 0) { if (Log.LOG) Log.d(LOG_TAG, "!! No mementos for " + mOriginalUrl); displayError("Sorry, there are no Mementos for this web page."); } else if (mMementos.size() > MAX_NUM_MEMENTOS_IN_LIST) showDialog(DIALOG_MEMENTO_YEARS); else showDialog(DIALOG_MEMENTO_DATES); } }; mFindMementos.execute((Void[]) null); }
From source file:com.maskyn.fileeditorpro.activity.MainActivity.java
void newFileToOpen(final GreatUri newUri, final String newFileText) { if (fileOpened && mEditor != null && mEditor.canSaveFile() && greatUri != null && pageSystem != null && currentEncoding != null) { new SaveFileDialog(greatUri, pageSystem.getAllText(mEditor.getText().toString()), currentEncoding, true, newUri).show(getFragmentManager(), "dialog"); return;// w w w. j a v a2 s. co m } new AsyncTask<Void, Void, Void>() { String message = ""; String fileText = ""; String fileName = ""; String encoding = "UTF-16"; boolean isRootRequired = false; ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); // Close the drawer mDrawerLayout.closeDrawer(Gravity.START); progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage(getString(R.string.please_wait)); progressDialog.show(); } @Override protected Void doInBackground(Void... params) { try { // if no new uri if (newUri == null || newUri.getUri() == null || newUri.getUri() == Uri.EMPTY) { fileExtension = "txt"; fileText = newFileText; } else { String filePath = newUri.getFilePath(); // if the uri has no path if (TextUtils.isEmpty(filePath)) { fileName = newUri.getFileName(); fileExtension = FilenameUtils.getExtension(fileName).toLowerCase(); readUri(newUri.getUri(), filePath, false); } // if the uri has a path else { fileName = FilenameUtils.getName(filePath); fileExtension = FilenameUtils.getExtension(fileName).toLowerCase(); isRootRequired = !newUri.isReadable(); // if we cannot read the file, root permission required if (isRootRequired) { readUri(newUri.getUri(), filePath, true); } // if we can read the file associated with the uri else { readUri(newUri.getUri(), filePath, false); } } } greatUri = newUri; } catch (Exception e) { message = e.getMessage(); fileText = ""; } while (mDrawerLayout.isDrawerOpen(Gravity.START)) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } private void readUri(Uri uri, String path, boolean asRoot) throws IOException { BufferedReader buffer = null; StringBuilder stringBuilder = new StringBuilder(); String line; if (asRoot) { encoding = "UTF-8"; // Connect the shared connection if (RootFW.connect()) { FileReader reader = RootFW.getFileReader(path); buffer = new BufferedReader(reader); } } else { boolean autoencoding = PreferenceHelper.getAutoEncoding(MainActivity.this); if (autoencoding) { encoding = FileUtils.getDetectedEncoding(getContentResolver().openInputStream(uri)); if (encoding.isEmpty()) { encoding = PreferenceHelper.getEncoding(MainActivity.this); } } else { encoding = PreferenceHelper.getEncoding(MainActivity.this); } InputStream inputStream = getContentResolver().openInputStream(uri); if (inputStream != null) { buffer = new BufferedReader(new InputStreamReader(inputStream, encoding)); } } if (buffer != null) { while ((line = buffer.readLine()) != null) { stringBuilder.append(line); stringBuilder.append("\n"); } buffer.close(); fileText = stringBuilder.toString(); } if (isRootRequired) RootFW.disconnect(); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); progressDialog.hide(); if (!TextUtils.isEmpty(message)) { Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); cannotOpenFile(); } else { pageSystem = new PageSystem(MainActivity.this, MainActivity.this, fileText); currentEncoding = encoding; aFileWasSelected(greatUri); showTextEditor(); if (fileName.isEmpty()) getSupportActionBar().setTitle(R.string.new_file); else getSupportActionBar().setTitle(fileName); if (greatUri != null) { refreshList(greatUri, true, false); } } } }.execute(); }
From source file:com.chatwing.whitelabel.activities.CommunicationActivity.java
@Override public void logout() { if (mUserManager.getCurrentUser() == null) { return;// www . jav a 2 s . co m } new AsyncTask<Void, Void, Void>() { public ProgressDialog dialog; @Override protected void onPreExecute() { super.onPreExecute(); dialog = ProgressDialog.show(getDialogContext(), "", getString(R.string.logging_out), true, false); } @Override protected Void doInBackground(Void... params) { try { String regId = mGcmManager.getRegistrationId(); mApiManager.updateGcm(mUserManager.getCurrentUser(), regId, ApiManager.GCM_ACTION_REMOVE); } catch (Exception e) { LogUtils.e(e); } mGcmManager.clearRegistrationId(); try { getContentResolver().applyBatch(ChatWingContentProvider.AUTHORITY, ChatWingContentProvider.getClearAllDataBatch()); } catch (Exception e) { LogUtils.e(e); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (dialog.isShowing()) { dialog.dismiss(); } mCurrentCommunicationMode.logout(); mUserManager.removeUsers(); mBus.post(ChatServiceEvent.unsubscribeAllChannels()); mCurrentCommunicationMode.deactivate(); Intent i = new Intent(CommunicationActivity.this, getEntranceActivityClass()); startActivity(i); finish(); } }.execute(); }
From source file:eu.operando.operandoapp.OperandoProxyStatus.java
private void DownloadInitialSettings() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getBoolean("firstTime", true) && haveNetworkConnection()) { // run one time code here final File tmp = new File(getFilesDir(), "domainfilters_" + System.currentTimeMillis()); try {//w ww . jav a 2 s.c o m new DownloadTask(MainActivity.this, new URL(DatabaseHelper.serverUrl + "/blocked_urls"), tmp, new DownloadTask.Listener() { @Override public void onCompleted() { new AsyncTask<Void, Void, Integer>() { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = ProgressDialog.show(MainActivity.this, null, "Applying up to date settings for your convenience, to keep you safe.\nThis might take while..."); dialog.setCancelable(false); } @Override protected Integer doInBackground(Void... params) { new DatabaseHelper(MainActivity.this) .deleteDomainFilterFile(DatabaseHelper.serverUrl); Integer count = 0; BufferedReader br = null; try { br = new BufferedReader(new FileReader(tmp)); String line; while ((line = br.readLine()) != null) { int hash = line.indexOf('#'); if (hash >= 0) line = line.substring(0, hash); line = line.trim(); try { String blockedDomain = line; if (blockedDomain.equals("local") || StringUtils.containsAny(blockedDomain, "localhost", "127.0.0.1", "broadcasthost")) continue; DomainFilter domainFilter = new DomainFilter(); domainFilter.setContent(blockedDomain); domainFilter.setSource(DatabaseHelper.serverUrl); domainFilter.setIsWildcard(false); new DatabaseHelper(MainActivity.this) .createDomainFilter(domainFilter); count++; } catch (Exception e) { Log.i("Error", "Invalid hosts file line: " + line); } } Log.i("Error", count + " entries read"); } catch (IOException ex) { Log.e("Error", ex.toString() + "\n" + Log.getStackTraceString(ex)); } finally { if (br != null) try { br.close(); } catch (IOException exex) { Log.e("Error", exex.toString() + "\n" + Log.getStackTraceString(exex)); } } return count; } @Override protected void onPostExecute(Integer count) { dialog.dismiss(); // mark first time has runned. SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("firstTime", false); editor.commit(); } }.execute(); } @Override public void onCancelled() { if (tmp.exists()) tmp.delete(); } @Override public void onException(Throwable ex) { if (tmp.exists()) tmp.delete(); ex.printStackTrace(); Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }).execute(); } catch (MalformedURLException mue) { mue.getMessage(); } } else if (!haveNetworkConnection()) { Toast.makeText(MainActivity.this, "You don't seem to have a working Internet Connection.", Toast.LENGTH_LONG).show(); } }
From source file:com.cssweb.android.common.FairyUI.java
private static void loadAllStock(final int paramInt1, final int paramInt2, final String paramString2, final String paramString3, final Context paramContext) { m_pDialog = new ProgressDialog(paramContext); m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); m_pDialog.setMessage(paramContext.getResources().getString(R.string.system_update_content)); m_pDialog.setIndeterminate(false);//from w ww. j ava2s. c o m m_pDialog.show(); new AsyncTask<Void, Void, Boolean>() { /** * ????? */ @Override protected Boolean doInBackground(Void... arg0) { boolean flag = true; JSONObject quoteData = null; try { quoteData = ConnService.getAllStock(); if (Utils.isHttpStatus(quoteData)) { CssIniFile.saveAllStockData(paramContext, CssIniFile.UserStockFile, quoteData.toString()); StockInfo.initAllStock(quoteData); StockInfo.allStock = quoteData; } else { flag = Boolean.FALSE; } } catch (JSONException e) { flag = Boolean.FALSE; } catch (Exception e) { flag = Boolean.FALSE; } return flag; } /** * ? */ protected void onPostExecute(Boolean result) { hiddenProgress(); if (result != Boolean.TRUE) { Toast.makeText(paramContext, R.string.load_data_error, Toast.LENGTH_SHORT).show(); } else { switchToWnd(paramInt1, paramInt2, paramString2, paramString3, paramContext); } } }.execute(); }
From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java
/** * This function initializes the tango ros node with RosJava interface. *//* w w w .ja v a2 s . c o m*/ private void initAndStartRosJavaNode() { this.nodeMainExecutorService.addListener(new NodeMainExecutorServiceListener() { @Override public void onShutdown(NodeMainExecutorService nodeMainExecutorService) { unbindFromTango(); mLogger.saveLogToFile(); // This ensures to kill the process started by the app. android.os.Process.killProcess(android.os.Process.myPid()); } }); if (mRunLocalMaster) { try { this.nodeMainExecutorService.startMaster(/*isPrivate*/ false); mMasterUri = this.nodeMainExecutorService.getMasterUri().toString(); // The URI returned by getMasterUri is correct but looks 'weird', // e.g. 'http://android-c90553518bc67cf5:1131'. // Instead of showing this to the user, we show the IP address of the device, // which is also correct and less confusing. WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); String deviceIP = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress()); mUriTextView = (TextView) findViewById(R.id.master_uri); mUriTextView.setText("http://" + deviceIP + ":11311"); } catch (RosRuntimeException e) { e.printStackTrace(); Log.e(TAG, getString(R.string.local_master_error)); displayToastMessage(R.string.local_master_error); return; } } if (mMasterUri != null) { URI masterUri; try { masterUri = URI.create(mMasterUri); } catch (IllegalArgumentException e) { Log.e(TAG, "Wrong URI: " + e.getMessage()); return; } this.nodeMainExecutorService.setMasterUri(masterUri); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { RunningActivity.this.init(nodeMainExecutorService); return null; } }.execute(); } else { Log.e(TAG, "Master URI is null"); } }
From source file:com.dngames.mobilewebcam.PhotoSettings.java
public static void GETSettings(final Context context) { // check for new settings when done final SharedPreferences prefs = context.getSharedPreferences(MobileWebCam.SHARED_PREFS_NAME, 0); final String settingsurl = prefs.getString("remote_config_url", ""); final int settingsfreq = Math.max(1, PhotoSettings.getEditInt(context, prefs, "remote_config_every", 1)); final String login = prefs.getString("remote_config_login", ""); final String password = prefs.getString("remote_config_password", ""); final boolean noToasts = prefs.getBoolean("no_messages", false); if (settingsurl.length() > 0 && gLastGETSettingsPictureCnt < MobileWebCam.gPictureCounter && (MobileWebCam.gPictureCounter % settingsfreq) == 0) { gLastGETSettingsPictureCnt = MobileWebCam.gPictureCounter; Handler h = new Handler(context.getMainLooper()); h.post(new Runnable() { @Override/*from ww w .ja v a 2 s . c o m*/ public void run() { new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); if (login.length() > 0) { try { ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials( new AuthScope(null, -1), new UsernamePasswordCredentials(login, password)); } catch (Exception e) { e.printStackTrace(); if (e.getMessage() != null) MobileWebCam.LogE("http login " + e.getMessage()); else MobileWebCam.LogE("http: unable to log in"); return null; } } HttpGet get = new HttpGet(settingsurl); HttpResponse response = httpclient.execute(get); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); InputStream is = buf.getContent(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder total = new StringBuilder(); String line; while ((line = r.readLine()) != null) total.append(line + "\n"); if (ht.getContentType().getValue().startsWith("text/plain")) return total.toString(); else return "GET Config Error!\n" + total.toString(); } catch (Exception e) { e.printStackTrace(); if (e.getMessage() != null) { MobileWebCam.LogE(e.getMessage()); return "GET Config Error!\n" + e.getMessage(); } } return null; } @Override protected void onPostExecute(String result) { if (result != null) { if (result.startsWith("GET Config Error!\n")) { if (!noToasts) Toast.makeText(context, result, Toast.LENGTH_SHORT).show(); } else { PhotoSettings.GETSettings(context, result, prefs); } } else if (!noToasts) Toast.makeText(context, "GET config failed!", Toast.LENGTH_SHORT).show(); } }.execute(); } }); } }
From source file:net.sourceforge.kalimbaradio.androidapp.activity.DownloadActivity.java
public void addTransactionEntry() { new AsyncTask<Void, Void, String>() { @Override//from w w w . j a v a 2s . co m protected String doInBackground(Void... params) { try { String songTitle = currentPlaying.getSong().getTitle(); String musicType = getDownloadService().isAd() ? "A" : "M"; SessionManager session = new SessionManager(getApplicationContext()); String cc = session.getUserDetails().get(SessionManager.KEY_CC); String mobileNo = session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER); HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); // String URL = Constants.PREFERENCES_KEY_SERVER_ADDRESS + "/rest/createUser.view?u=admin&p=kalimba&username=" + URLEncoder.encode(session.getUserDetails().get(SessionManager.KEY_SUBUSER), "UTF-8") + "&password=" + URLEncoder.encode(Constants.PREFERENCES_KEY_SERVER_USER_PASSWORD, "UTF-8") + "&email=" + URLEncoder.encode(session.getUserDetails().get(SessionManager.KEY_SUBUSER) + "@kalimbaradio.com", "UTF-8") + "&v=1.10.2&c=myapp&f=json"; String URL = Constants.PREFERENCES_REST_SERVER_ADDRESS + "/RESTFull/REST/Report/AddTransaction?cc=" + URLEncoder.encode(cc, "UTF-8") + "&mobile_no=" + URLEncoder.encode(mobileNo, "UTF-8") + "&song_name=" + URLEncoder.encode(songTitle, "UTF-8") + "&music_type=" + URLEncoder.encode(musicType, "UTF-8"); HttpGet httpGet = new HttpGet(URL); HttpResponse response = httpClient.execute(httpGet, localContext); // Toast.makeText(getApplicationContext(), response.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } return "Works"; } }.execute(null, null, null); }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override//w w w .j a v a 2 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); }