List of usage examples for android.app AlertDialog.Builder show
public void show()
From source file:com.zira.registration.DocumentUploadActivity.java
@Override public void processFinish(String output, String methodName) { // obj;/*from w w w . j a va 2 s . co m*/ //Log.e("doucment", output); if (methodName.equalsIgnoreCase(uploadImageMethod)) { Log.e("doucment", output); /*try { //JSONObject obj = new JSONObject(output); // String jsonMessage=obj.getString("message"); //String jsonMessage1=obj.getString("result"); // System.err.println("messgage=="+jsonMessage+"result="+jsonMessage1); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } if (methodName.equalsIgnoreCase(driverRegMethod)) { Log.e("driver update", output); try { JSONObject obj = new JSONObject(output); String jsonResult = obj.getString("result"); String jsonMessage = obj.getString("message"); if (jsonResult.equals("0")) { //Util.alertMessage(DocumentUploadActivity.this, jsonMessage); //editor.clear(); //editor.commit(); AlertDialog.Builder alert = new AlertDialog.Builder(DocumentUploadActivity.this); alert.setTitle("Zira24/7"); alert.setMessage("Registration successful"); alert.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { //System.err.println("messgage=="+jsonMessage+" "+jsonResult); // Toast.makeText(DocumentUploadActivity.this, jsonMessage, 1).show(); SingleTon.getInstance().setEdited(false); mProfileInfoModel.setVechile_make(SingleTon.getInstance().getVehicleMake()); mProfileInfoModel.setVechile_model(SingleTon.getInstance().getVehicleModel()); mProfileInfoModel.setVechile_year(SingleTon.getInstance().getVehicleYear()); mProfileInfoModel .setLicenseplatenumber(SingleTon.getInstance().getVehicleLicencePlateNumber()); mProfileInfoModel .setLicenseplatecountry(SingleTon.getInstance().getVehicleCountryName()); mProfileInfoModel.setLicenseplatestate(SingleTon.getInstance().getVehicleStateName()); mProfileInfoModel.setAddress(SingleTon.getInstance().getBg_address1() + ""); mProfileInfoModel.setAddress1(SingleTon.getInstance().getBg_address1()); mProfileInfoModel.setAddress2("");//SingleTon.getInstance().getBg_address2()); mProfileInfoModel.setCity(SingleTon.getInstance().getBg_city()); mProfileInfoModel.setState(SingleTon.getInstance().getBg_drivingLicenseState()); mProfileInfoModel.setZipcode(SingleTon.getInstance().getBg_zipcode()); mProfileInfoModel .setDrivinglicensenumber(SingleTon.getInstance().getBg_drivingLicenseNumber()); mProfileInfoModel .setDrivinglicensestate(SingleTon.getInstance().getBg_drivingLicenseState()); mProfileInfoModel .setDrivinglicenseexpirationdate(SingleTon.getInstance().getBg_LicExoDate()); mProfileInfoModel.setDateofbirth(SingleTon.getInstance().getBgDOB()); mProfileInfoModel .setSocialsecuritynumber(SingleTon.getInstance().getBg_socialSecNumber()); SingleTon.getInstance().setProfileInfoModel(mProfileInfoModel); getProfileInfo(); //finish(); } }); alert.show(); /*if(prefs.getString("mode", "").equals("rider")) { Intent i=new Intent(DocumentUploadActivity.this,VehicleSearchActivity.class); finish(); startActivity(i); } else if(prefs.getString("mode", "").equals("driver")) { //Intent i=new Intent(DocumentUploadActivity.this,DriverModeActivity.class); finish(); //startActivity(i); }*/ } else { Util.alertMessage(DocumentUploadActivity.this, jsonMessage); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (methodName.equalsIgnoreCase(GetProfile)) { Log.e("getprofile=", output); mProfileInfoModel = ziraParser.profileInfo(output); SingleTon.getInstance().setProfileInfoModel(mProfileInfoModel); Intent i = new Intent(DocumentUploadActivity.this, GetProfile.class); startActivity(i); finish(); } }
From source file:com.example.zf_android.activity.MerchantEdit.java
private void show3Dialog(int type, final String uri) { AlertDialog.Builder builder = new AlertDialog.Builder(MerchantEdit.this); final String[] items = getResources().getStringArray(R.array.apply_detail_view); MerchantEdit.this.type = type; builder.setItems(items, new DialogInterface.OnClickListener() { @Override/*from w w w . j a v a2s . com*/ public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: { AlertDialog.Builder build = new AlertDialog.Builder(MerchantEdit.this); LayoutInflater factory = LayoutInflater.from(MerchantEdit.this); final View textEntryView = factory.inflate(R.layout.show_view, null); build.setView(textEntryView); final ImageView view = (ImageView) textEntryView.findViewById(R.id.imag); // ImageCacheUtil.IMAGE_CACHE.get(uri, view); ImageLoader.getInstance().displayImage(uri, view, options); build.create().show(); break; } case 1: { Intent intent; if (Build.VERSION.SDK_INT < 19) { intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); } else { intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } startActivityForResult(intent, REQUEST_UPLOAD_IMAGE); break; } case 2: { String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); if (!outDir.exists()) { outDir.mkdirs(); } File outFile = new File(outDir, System.currentTimeMillis() + ".jpg"); photoPath = outFile.getAbsolutePath(); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile)); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, REQUEST_TAKE_PHOTO); } else { CommonUtil.toastShort(MerchantEdit.this, getString(R.string.toast_no_sdcard)); } break; } } } }); builder.show(); }
From source file:uk.co.senab.photoview.sample.ViewPagerActivity.java
@Override public void onBackPressed() { final AlertDialog.Builder alertbox5 = new AlertDialog.Builder(ViewPagerActivity.this); alertbox5.setTitle("Rate Us!"); alertbox5.setIcon(android.R.drawable.stat_notify_error); alertbox5.setMessage(//from ww w.j ava 2 s . c o m "Please rate us and leave a suggestion so we can enhance this app to your liking! Once you rate, this dialog box won't show again."); alertbox5.setNeutralButton("Rate", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { editor.putInt("continuePage", mViewPager.getCurrentItem()); editor.commit(); rated = true; editor.putBoolean("rated", rated); editor.commit(); String appName2 = "com.qaziconsultancy.thirteenlinequran"; try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName2))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName2))); } } }); alertbox5.setNegativeButton("Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { editor.putInt("continuePage", mViewPager.getCurrentItem()); editor.commit(); finish(); } }); if (!rated) alertbox5.show(); else { editor.putInt("continuePage", mViewPager.getCurrentItem()); editor.commit(); finish(); } }
From source file:com.ccxt.whl.activity.SettingsFragment.java
/** * ?//from w w w . j av a 2s.c o m */ private void change_zhiye() { // TODO Auto-generated method stub AlertDialog.Builder builder = new Builder(getActivity()); String[] strarr = { "/?/", "//", "/?/??", "?///?", "//", "?//", "/?/?", "/", "/", "/??", "", "" }; builder.setItems(strarr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { String zhiye = ""; switch (arg1) { case 0: zhiye = "/?/"; break; case 1: zhiye = "//"; break; case 2: zhiye = "/?/??"; break; case 3: zhiye = "?///?"; break; case 4: zhiye = "//"; break; case 5: zhiye = "?//"; break; case 6: zhiye = "/?/?"; break; case 7: zhiye = "/"; break; case 8: zhiye = "/"; break; case 9: zhiye = "/??"; break; case 10: zhiye = ""; break; default: zhiye = ""; break; } RequestParams params = new RequestParams(); params.add("user", DemoApplication.getInstance().getUser()); params.add("zhiye", zhiye); params.add("param", "zhiye"); params.add("uid", uid); HttpRestClient.get(Constant.UPDATE_USER_URL, params, responseHandler); pd.show(); } }); builder.show(); }
From source file:ar.com.tristeslostrestigres.diasporanativewebapp.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.notifications) { if (Helpers.isOnline(MainActivity.this)) { // webView.stopLoading(); ////from ww w .j a v a 2s.co m // WebView wvNotifications = new WebView(MainActivity.this); // wvNotifications.loadUrl("https://" + podDomain + "/notifications"); // // final AlertDialog d = new AlertDialog.Builder(MainActivity.this).setView(wvNotifications) // .setPositiveButton("Close", new DialogInterface.OnClickListener() { // @TargetApi(11) // public void onClick(DialogInterface dialog, int id) { // dialog.cancel(); // } // }).show(); // //// wvNotifications.setWebChromeClient(new WebChromeClient() { //// //// public void onProgressChanged(WebView view, int progress) { //// progressBar.setProgress(progress); // //// if (progress > 0 && progress <= 60) { //// view.loadUrl("javascript: ( function() {" + //// " if (document.getElementById('notification')) {" + //// " var count = document.getElementById('notification').innerHTML;" + //// " NotificationCounter.setNotificationCount(count.replace(/(\\r\\n|\\n|\\r)/gm, \"\"));" + //// " } else {" + //// " NotificationCounter.setNotificationCount('0');" + //// " }" + //// " if (document.getElementById('conversation')) {" + //// " var count = document.getElementById('conversation').innerHTML;" + //// " NotificationCounter.setConversationCount(count.replace(/(\\r\\n|\\n|\\r)/gm, \"\"));" + //// " } else {" + //// " NotificationCounter.setConversationCount('0');" + //// " }" + //// "})();"); //// } // //// if (progress > 60) { //// view.loadUrl("javascript: ( function() {" + //// " if(document.getElementById('main_nav')) {" + //// " document.getElementById('main_nav').parentNode.removeChild(" + //// " document.getElementById('main_nav'));" + //// " } else if (document.getElementById('main-nav')) {" + //// " document.getElementById('main-nav').parentNode.removeChild(" + //// " document.getElementById('main-nav'));" + //// " }" + //// "})();"); ////// fab.setVisibility(View.VISIBLE); //// } // //// if (progress == 100) { //// fab.collapse(); //// progressBar.setVisibility(View.GONE); //// } else { //// progressBar.setVisibility(View.VISIBLE); //// } //// } //// }); // // wvNotifications.setWebViewClient(new WebViewClient() { // @Override // public boolean shouldOverrideUrlLoading(WebView view, String url) { // if (!url.equals("https://" + podDomain + "/notifications")) { // Intent urlIntent = new Intent(MainActivity.URL_MESSAGE); // urlIntent.putExtra("url", url); // sendBroadcast(urlIntent); // } // d.dismiss(); // return true; // } // }); webView.loadUrl("https://" + podDomain + "/notifications"); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } if (id == R.id.conversations) { if (Helpers.isOnline(MainActivity.this)) { webView.loadUrl("https://" + podDomain + "/conversations"); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } if (id == R.id.search) { fab.collapse(); if (Helpers.isOnline(MainActivity.this)) { final AlertDialog.Builder alert = new AlertDialog.Builder(this); final EditText input = new EditText(this); alert.setView(input); alert.setTitle(R.string.search_alert_title); alert.setPositiveButton(R.string.search_alert_people, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputTag = input.getText().toString().trim(); String cleanTag = inputTag.replaceAll("\\*", ""); // this validate the input data for tagfind if (cleanTag.isEmpty()) { dialog.cancel(); // if user dont have added a tag Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.search_alert_bypeople_validate_needsomedata, Snackbar.LENGTH_LONG) .show(); } else { // User have added a search tag txtTitle.setText(R.string.fab1_title_person); webView.loadUrl("https://" + podDomain + "/people.mobile?q=" + cleanTag); } } }).setNegativeButton(R.string.search_alert_tag, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputTag = input.getText().toString().trim(); String cleanTag = inputTag.replaceAll("\\#", ""); // this validate the input data for tagfind if (cleanTag.isEmpty()) { dialog.cancel(); // if user hasn't added a tag Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.search_alert_bytags_validate_needsomedata, Snackbar.LENGTH_LONG) .show(); } else { // User have added a search tag txtTitle.setText(R.string.fab1_title_tag); webView.loadUrl("https://" + podDomain + "/tags/" + cleanTag); } } }).setNeutralButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // } }); alert.show(); } } if (id == R.id.reload) { if (Helpers.isOnline(MainActivity.this)) { webView.reload(); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } if (id == R.id.mobile) { if (Helpers.isOnline(MainActivity.this)) { webView.loadUrl("https://" + podDomain + "/mobile/toggle"); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } if (id == R.id.loadImg) { if (Helpers.isOnline(MainActivity.this)) { wSettings.setLoadsImagesAutomatically(!pm.getLoadImages()); pm.setLoadImages(!pm.getLoadImages()); webView.loadUrl(webView.getUrl()); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } if (id == R.id.fontSize) { if (Helpers.isOnline(MainActivity.this)) { alertFormElements(); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } if (id == R.id.exit) { if (Helpers.isOnline(MainActivity.this)) { new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert) .setMessage(getString(R.string.confirm_sign_out)) .setPositiveButton(getString(android.R.string.yes).toUpperCase(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { webView.clearCache(true); Intent i = new Intent(MainActivity.this, PodsActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); finish(); } }) .setNegativeButton(getString(android.R.string.no).toUpperCase(), null).show(); return true; } else { Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT) .show(); return false; } } return super.onOptionsItemSelected(item); }
From source file:com.hackensack.umc.activity.RegistrationDetailsActivity.java
public void showAlert(Context context, String message, String title, final OuterQuetions outerQuetions) { // new android.app.AlertDialog.Builder(context) // .setTitle(title) // .setMessage(message) // .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // /*Bundle b = new Bundle(); // b.putParcelable(Constant.QUETIONS_DATA, outerQuetions); // b.putString(Constant.EMAIL_ID, mEmail.getText().toString()); // b.putParcelable(Constant.PATIENT_FOR_EPIC_CALL, cretepationToSendForEpicCall());*/ ///*from www . j ava 2 s .c o m*/ // Intent intent = new Intent(RegistrationDetailsActivity.this, QuetionsActivity.class); // intent.putExtra(Constant.QUETIONS_DATA, outerQuetions); // if (mInsuranceInfo == null) { // mInsuranceInfo = new InsuranceInfo(); // } // intent.putExtra(Constant.INSURANCE_DATA_TO_SEND, new CoverageJsonCreator(mInsuranceInfo.getPlanProvider(), mInsuranceInfo.getMemberNumber(), mInsuranceInfo.getGroupNumber(), mInsuranceInfo.getSubscriberId(), mInsuranceInfo.getReference(), mInsuranceInfo.getSubscriberName(), mInsuranceInfo.getSubscriberDateOfBirth())); // intent.putExtra(Constant.EMAIL_ID, mEmail.getText().toString()); // intent.putExtra(Constant.PATIENT_FOR_EPIC_CALL, createPationToSendForEpicCall()); // // intent.putExtra("bundle", b); // startActivity(intent); // } // }) // .setCancelable(false) // .show(); if (!isFinishing()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(false); LayoutInflater inflater = getLayoutInflater(); View dialogView = inflater.inflate(R.layout.dialog_network_offline, null); builder.setView(dialogView); ((TextView) dialogView.findViewById(R.id.dialog_title)).setText(title); ((TextView) dialogView.findViewById(R.id.text_message)).setText(message); Button btnDismiss = (Button) dialogView.findViewById(R.id.button_dialog_ok); btnDismiss.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { alert.dismiss(); Intent intent = new Intent(RegistrationDetailsActivity.this, QuetionsActivity.class); intent.putExtra(Constant.QUETIONS_DATA, outerQuetions); if (mInsuranceInfo == null) { mInsuranceInfo = new InsuranceInfo(); } //with nwe json creator. intent.putExtra(Constant.INSURANCE_DATA_TO_SEND, new CoverageJsonCreatorNew(mInsuranceInfo.getPlanProvider(), mInsuranceInfo.getMemberNumber(), mInsuranceInfo.getGroupNumber(), mInsuranceInfo.getSubscriberId(), mInsuranceInfo.getReference(), mInsuranceInfo.getSubscriberName(), mInsuranceInfo.getSubscriberDateOfBirth())); intent.putExtra(Constant.EMAIL_ID, mEmail.getText().toString()); intent.putExtra(Constant.PATIENT_FOR_EPIC_CALL, createPationToSendForEpicCall()); intent.putExtra(Constant.PARENTS_BIRTHDATE, birthDate); intent.putExtra(Constant.PARENTS_FIRST_NAME, fName); intent.putExtra(Constant.PARENTS_LAST_NAME, lastName); intent.putExtra(Constant.PARENTS_GENDER, gender); // intent.putExtra("bundle", b); startActivity(intent); } }); alert = builder.show(); } }
From source file:com.googlecode.android_scripting.facade.ui.NFCBeamTask.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi") @Override/*from w w w . java 2 s .com*/ public void onCreate() { super.onCreate(); if (initNFCBeam()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); if (mTitle != null) { builder.setTitle(mTitle); } // Can't display both a message and items. We'll elect to show the items instead. if (mMessage != null && mItems.isEmpty()) { builder.setMessage(mMessage); } switch (mInputType) { // Add single choice menu items to dialog. case SINGLE_CHOICE: builder.setSingleChoiceItems(getItemsAsCharSequenceArray(), mSelectedItems.iterator().next(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { mSelectedItems.clear(); mSelectedItems.add(item); } }); break; // Add multiple choice items to the dialog. case MULTI_CHOICE: boolean[] selectedItems = new boolean[mItems.size()]; for (int i : mSelectedItems) { selectedItems[i] = true; } builder.setMultiChoiceItems(getItemsAsCharSequenceArray(), selectedItems, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int item, boolean isChecked) { if (isChecked) { mSelectedItems.add(item); } else { mSelectedItems.remove(item); } } }); break; // Add standard, menu-like, items to dialog. case MENU: builder.setItems(getItemsAsCharSequenceArray(), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Map<String, Integer> result = new HashMap<String, Integer>(); result.put("item", item); dismissDialog(); setResult(result); } }); break; case PLAIN_TEXT: mEditText = new EditText(getActivity()); if (mDefaultText != null) { mEditText.setText(mDefaultText); } mEditText.setInputType(mEditInputType); builder.setView(mEditText); break; case PASSWORD: mEditText = new EditText(getActivity()); mEditText.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); mEditText.setTransformationMethod(new PasswordTransformationMethod()); builder.setView(mEditText); break; default: // No input type specified. } configureButtons(builder, getActivity()); addOnCancelListener(builder, getActivity()); mDialog = builder.show(); mShowLatch.countDown(); } else { } }
From source file:com.stikyhive.stikyhive.ChattingActivity.java
public void showPhoto() { AlertDialog.Builder builder = new AlertDialog.Builder(this); String[] strArray = { "Take photo", "Choose from Gallery" }; builder.setTitle("Select Photo").setItems(strArray, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // The 'which' argument contains the index position // of the selected item switch (which) { case 0: Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); /*****// ww w. j a v a 2s . com * Define the file-name to save photo taken by * Camera activity *******/ String fileName = "Camera_Example.jpg"; // Create parameters for Intent with filename ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, fileName); values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera"); /****** * imageUri is the current activity attribute, * define and save it for later usage *****/ imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // start the image capture Intent startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); Log.i("Camera ", " Testing..."); break; case 1: // start GalleryUtil Activity to choose photo from // Gallery Intent gallery_Intent = new Intent("com.arctech.GALLERYUTIL"); gallery_Intent.putExtra("type", "image"); startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE); break; default: break; } } }); builder.create(); builder.show(); }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override//from ww w . j av a 2 s .co 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); }