List of usage examples for android.widget Button Button
public Button(Context context)
From source file:com.amazon.android.ui.fragments.ErrorDialogFragment.java
/** * Creates the action button.//ww w . j a v a 2s. c o m * * @param actionLabel The text to be displayed on the action button. * @return The instantiated button. */ private Button createActionButton(String actionLabel) { Button button = new Button(getActivity()); button.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.action_button_background)); button.setText(actionLabel); CalligraphyUtils.applyFontToTextView(getActivity(), button, ConfigurationManager.getInstance(getActivity()) .getTypefacePath(ConfigurationConstants.REGULAR_FONT)); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); int margin = (int) getResources().getDimension(R.dimen.error_button_side_margin); params.setMargins(margin, 0, margin, 0); button.setLayoutParams(params); button.setTextColor( ContextCompat.getColorStateList(getActivity(), R.color.action_button_text_color_selector)); button.setFocusable(true); button.setFocusableInTouchMode(true); button.setNextFocusDownId(button.getId()); button.setNextFocusUpId(button.getId()); button.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.action_button_background)); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.doButtonClick(ErrorDialogFragment.this, ErrorUtils.getErrorButtonType(ErrorDialogFragment.this.getActivity(), (((TextView) v).getText()).toString()), (ErrorUtils.ERROR_CATEGORY) getArguments().get(ARG_ERROR_CATEGORY)); } }); return button; }
From source file:com.eurotong.orderhelperandroid.OrderMenuActivity.java
private void MakeMenuGroupButtons() { menusContainer.removeAllViews();// w w w. j av a 2s . co m try { for (VMMenuGroup group : _lstVMMenuGroup) { Button btn = new Button(this); btn.setText(group.GroupName); btn.setTag(group); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MakeMenuGroupList(v); } }); menusContainer.addView(btn); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.aosijia.dragonbutler.ui.widget.ActionSheet.java
private void createItems() { String[] titles = getOtherButtonTitles(); if (titles != null) { for (int i = 0; i < titles.length; i++) { Button bt = new Button(getActivity()); bt.setId(CANCEL_BUTTON_ID + i + 1); bt.setOnClickListener(this); bt.setBackgroundDrawable(getOtherButtonBg(titles, i)); bt.setText(titles[i]);/*ww w . jav a2s. c o m*/ bt.setTextColor(mAttrs.otherButtonTextColor); bt.setTextSize(TypedValue.COMPLEX_UNIT_PX, mAttrs.actionSheetTextSize); if (i > 0) { LinearLayout.LayoutParams params = createButtonLayoutParams(); params.topMargin = mAttrs.otherButtonSpacing; mPanel.addView(bt, params); } else { mPanel.addView(bt); } } } Button bt = new Button(getActivity()); bt.getPaint().setFakeBoldText(true); bt.setTextSize(TypedValue.COMPLEX_UNIT_PX, mAttrs.actionSheetTextSize); bt.setId(ActionSheet.CANCEL_BUTTON_ID); bt.setBackgroundDrawable(mAttrs.cancelButtonBackground); bt.setText(getCancelButtonTitle()); bt.setTextColor(mAttrs.cancelButtonTextColor); bt.setOnClickListener(this); LinearLayout.LayoutParams params = createButtonLayoutParams(); params.topMargin = mAttrs.cancelButtonMarginTop; mPanel.addView(bt, params); mPanel.setBackgroundDrawable(mAttrs.background); mPanel.setPadding(mAttrs.padding, mAttrs.padding, mAttrs.padding, mAttrs.padding); }
From source file:nyc.c4q.jordansmith.finefree.ActivityMain.java
private void setupCarMenu() { for (int i = 0; i < cars.size(); i++) { submenu.clear();/* www.jav a2 s .c o m*/ submenu.add(cars.get(i).getName()).setTitle(cars.get(i).getName().toString()) .setIcon(R.drawable.ic_car_black_36dp); final MenuItem item = submenu.getItem(i); Button button = new Button(this); button.setText("Remove"); button.setTextColor(ContextCompat.getColor(this, R.color.white)); item.setActionView(button); button.setBackground(getDrawable(R.drawable.button_shape)); item.getActionView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(ActivityMain.this).setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Delete Car").setMessage("Are you sure you want to remove car?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { System.out.println("CLICKED " + item.getTitle()); cupboard().withDatabase(db).delete(Car.class, "name = ?", (String) item.getTitle()); updateSubmenu(); } }).setNegativeButton("Cancel", null).show(); } }); } }
From source file:com.todoroo.astrid.notes.EditNoteActivity.java
private void setUpListAdapter() { items.clear();/*from w w w. ja va2s.co m*/ this.removeAllViews(); metadataDao.byTaskAndKey(task.getId(), NoteMetadata.METADATA_KEY, new Callback<Metadata>() { @Override public void apply(Metadata metadata) { items.add(NoteOrUpdate.fromMetadata(metadata)); } }); userActivityDao.getCommentsForTask(task.getUuid(), new Callback<UserActivity>() { @Override public void apply(UserActivity update) { items.add(NoteOrUpdate.fromUpdate(update)); } }); Collections.sort(items, new Comparator<NoteOrUpdate>() { @Override public int compare(NoteOrUpdate a, NoteOrUpdate b) { if (a.createdAt < b.createdAt) { return 1; } else if (a.createdAt == b.createdAt) { return 0; } else { return -1; } } }); for (int i = 0; i < Math.min(items.size(), commentItems); i++) { View notesView = this.getUpdateNotes(items.get(i), this); this.addView(notesView); } if (items.size() > commentItems) { Button loadMore = new Button(getContext()); loadMore.setText(R.string.TEA_load_more); loadMore.setTextColor(activity.getResources().getColor(R.color.task_edit_deadline_gray)); loadMore.setBackgroundColor(Color.alpha(0)); loadMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Perform action on click commentItems += 10; setUpListAdapter(); } }); this.addView(loadMore); } for (UpdatesChangedListener l : listeners) { l.updatesChanged(); } }
From source file:com.googlecode.android_scripting.activity.Main.java
protected void initializeViews() { LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); layout.setGravity(Gravity.CENTER_HORIZONTAL); TextView textview = new TextView(this); textview.setText(" PhpForAndroid " + version); ImageView imageView = new ImageView(this); imageView.setImageDrawable(getResources().getDrawable(R.drawable.pfa)); layout.addView(imageView);/*from w ww . ja v a 2s. co m*/ mButton = new Button(this); mAboutButton = new Button(this); MarginLayoutParams marginParams = new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); final float scale = getResources().getDisplayMetrics().density; int marginPixels = (int) (MARGIN_DIP * scale + 0.5f); marginParams.setMargins(marginPixels, marginPixels, marginPixels, marginPixels); mButton.setLayoutParams(marginParams); mAboutButton.setLayoutParams(marginParams); layout.addView(textview); layout.addView(mButton); layout.addView(mAboutButton); mProgressLayout = new LinearLayout(this); mProgressLayout.setOrientation(LinearLayout.HORIZONTAL); mProgressLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mProgressLayout.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); LinearLayout bottom = new LinearLayout(this); bottom.setOrientation(LinearLayout.HORIZONTAL); bottom.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); bottom.setGravity(Gravity.CENTER_VERTICAL); mProgressLayout.addView(bottom); TextView message = new TextView(this); message.setText(" In Progress..."); message.setTextSize(20); message.setTypeface(Typeface.DEFAULT_BOLD); message.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); ProgressBar bar = new ProgressBar(this); bar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); bottom.addView(bar); bottom.addView(message); mProgressLayout.setVisibility(View.INVISIBLE); layout.addView(mProgressLayout); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarIndeterminateVisibility(false); setContentView(layout); }
From source file:busradar.madison.StopDialog.java
StopDialog(final Context ctx, final int stopid, final int lat, final int lon) { super(ctx);/*from w w w. ja v a 2 s . c o m*/ this.stopid = stopid; // getWindow().requestFeature(Window.FEATURE_LEFT_ICON); getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); final String name = DB.getStopName(stopid); setTitle(name); routes = get_time_urls(StopDialog.this.stopid); // getWindow().setLayout(LayoutParams.FILL_PARENT, // LayoutParams.FILL_PARENT); setContentView(new RelativeLayout(ctx) { { addView(new TextView(ctx) { { setId(stop_num_id); setText(Html.fromHtml(String.format( "[<a href='http://www.cityofmadison.com/metro/BusStopDepartures/StopID/%04d.pdf'>%04d</a>]", stopid, stopid))); setPadding(0, 0, 5, 0); this.setMovementMethod(LinkMovementMethod.getInstance()); } }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) { { addRule(ALIGN_PARENT_RIGHT); } }); addView(new ImageView(ctx) { boolean enabled; @Override public void setEnabled(boolean e) { enabled = e; setImageResource(e ? R.drawable.love_enabled : R.drawable.love_disabled); if (e) { G.favorites.add_favorite_stop(stopid, name, lat, lon); Toast.makeText(ctx, "Added stop to Favorites", Toast.LENGTH_SHORT).show(); } else { G.favorites.remove_favorite_stop(stopid); Toast.makeText(ctx, "Removed stop from Favorites", Toast.LENGTH_SHORT).show(); } } { enabled = G.favorites.is_stop_favorite(stopid); setImageResource(enabled ? R.drawable.love_enabled : R.drawable.love_disabled); setPadding(0, 0, 10, 0); setOnClickListener(new OnClickListener() { public void onClick(View v) { setEnabled(!enabled); } }); } }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) { { addRule(LEFT_OF, stop_num_id); setMargins(0, -3, 0, 0); } }); addView(cur_loading_text = new TextView(ctx) { { setText("Loading..."); setPadding(5, 0, 0, 0); } }); addView(new HorizontalScrollView(ctx) { { setId(route_list_id); setHorizontalScrollBarEnabled(false); addView(new LinearLayout(ctx) { float text_size; Button cur_button; { int last_route = -1; for (int i = 0; i < routes.length; i++) { final RouteURL route = routes[i]; if (route.route == last_route) continue; last_route = route.route; addView(new Button(ctx) { public void setEnabled(boolean e) { if (e) { setBackgroundColor(0xff000000 | G.route_points[route.route].color); setTextSize(TypedValue.COMPLEX_UNIT_PX, text_size * 1.5f); } else { setBackgroundColor(0x90000000 | G.route_points[route.route].color); setTextSize(TypedValue.COMPLEX_UNIT_PX, text_size); } } { setText(G.route_points[route.route].name); setTextColor(0xffffffff); setTypeface(Typeface.DEFAULT_BOLD); text_size = getTextSize(); if (G.active_route == route.route) { setEnabled(true); cur_button = this; } else setEnabled(false); final Button b = this; setOnClickListener(new OnClickListener() { public void onClick(View v) { if (cur_button != null) { cur_button.setEnabled(false); } if (cur_button == b) { cur_button.setEnabled(false); cur_button = null; selected_route = null; update_time_display(); } else { cur_button = b; cur_button.setEnabled(true); selected_route = route; update_time_display(); } } }); } }); } } }); } }, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) { { addRule(RelativeLayout.BELOW, stop_num_id); addRule(RelativeLayout.CENTER_HORIZONTAL); } }); addView(status_text = new TextView(ctx) { { setText(""); } }, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) { { addRule(RelativeLayout.BELOW, route_list_id); addRule(RelativeLayout.CENTER_HORIZONTAL); } }); addView(list_view = new ListView(ctx) { { setId(time_list_id); setVerticalScrollBarEnabled(false); setAdapter(times_adapter = new BaseAdapter() { public View getView(final int position, View convertView, ViewGroup parent) { CellView v; if (convertView == null) v = new CellView(ctx); else v = (CellView) convertView; RouteTime rt = curr_times.get(position); v.setBackgroundColor(G.route_points[rt.route].color | 0xff000000); v.route_textview.setText(G.route_points[rt.route].name); if (rt.dir != null) v.dir_textview.setText("to " + rt.dir); v.time_textview.setText(rt.time); return v; } public int getCount() { return curr_times.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } }); } }, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) { { addRule(RelativeLayout.BELOW, route_list_id); } }); } }); TextView title = (TextView) findViewById(android.R.id.title); title.setEllipsize(TextUtils.TruncateAt.MARQUEE); title.setSelected(true); title.setTextColor(0xffffffff); title.setMarqueeRepeatLimit(-1); // getWindow().set, value) // getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, // android.R.drawable.ic_dialog_info); // title.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL); if (G.active_route >= 0) for (int i = 0; i < routes.length; i++) if (routes[i].route == G.active_route) { selected_route = routes[i]; RouteURL[] rnew = new RouteURL[routes.length]; rnew[0] = selected_route; for (int j = 0, k = 1; j < routes.length; j++) if (j != i) rnew[k++] = routes[j]; routes = rnew; break; } update_time_display(); }
From source file:tinygsn.gui.android.ActivityViewDataNew.java
private void addTableViewModeLatest() { table_view_mode = (TableLayout) findViewById(R.id.table_view_mode); // table_view_mode.setLayoutParams(new // TableLayout.LayoutParams(LayoutParams.FILL_PARENT, // LayoutParams.WRAP_CONTENT)); table_view_mode.removeAllViews();//from www .java 2 s. com TableRow row = new TableRow(this); TextView txt = new TextView(this); txt.setText(" View "); txt.setTextColor(Color.parseColor("#000000")); row.addView(txt); final EditText editText_numLatest = new EditText(this); editText_numLatest.setText("10"); editText_numLatest.setInputType(InputType.TYPE_CLASS_NUMBER); editText_numLatest.requestFocus(); editText_numLatest.setTextColor(Color.parseColor("#000000")); row.addView(editText_numLatest); editText_numLatest.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { try { numLatest = Integer.parseInt(editText_numLatest.getText().toString()); loadLatestData(); } catch (NumberFormatException e) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("Please input a number!"); } } }); txt = new TextView(this); txt.setText(" latest values"); txt.setTextColor(Color.parseColor("#000000")); row.addView(txt); txt = new TextView(this); txt.setText(" "); row.addView(txt); table_view_mode.addView(row); row = new TableRow(this); Button detailBtn = new Button(this); detailBtn.setText("Detail"); // detailBtn.setBackground(getResources().getDrawable(R.drawable.info)); // detailBtn.setWidth(200); detailBtn.setTextSize(TEXT_SIZE + 2); detailBtn.setTextColor(Color.parseColor("#000000")); detailBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialogDetail(); } }); Button plotDataBtn = new Button(this); plotDataBtn.setText("Plot data"); plotDataBtn.setTextSize(TEXT_SIZE + 2); plotDataBtn.setTextColor(Color.parseColor("#000000")); // plotDataBtn.setBackground(getResources().getDrawable(R.drawable.chart)); // LinearLayout.LayoutParams params = plotDataBtn.getLayoutParams(); // params.width = 50; // plotDataBtn.setLayoutParams(params); plotDataBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { viewChart(); } }); TableRow.LayoutParams rowParams = new TableRow.LayoutParams(); // params.addRule(TableRow.LayoutParams.FILL_PARENT); rowParams.span = 2; row.addView(detailBtn, rowParams); row.addView(plotDataBtn, rowParams); // detailBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, // LayoutParams.WRAP_CONTENT)); // plotDataBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, // LayoutParams.WRAP_CONTENT)); row.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); table_view_mode.addView(row); }
From source file:com.TaxiDriver.jy.CameraPreview.java
Preview(Context context) { super(context); mSurfaceView = new SurfaceView(context); snap = new Button(context); addView(mSurfaceView);/*from w w w . j a v a 2 s .co m*/ // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = mSurfaceView.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override/*from w ww . jav a 2 s. c om*/ 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); }