@ZeroGeek
2016-08-03T01:33:15.000000Z
字数 7101
阅读 964
android
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {Reader reader = null;reader = new InputStreamReader(stream, "UTF-8");char[] buffer = new char[len];reader.read(buffer);return new String(buffer);}
private InputStream downloadUrl(String urlString) throws IOException {// BEGIN_INCLUDE(get_inputstream)URL url = new URL(urlString);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);// Start the queryconn.connect();InputStream stream = conn.getInputStream();return stream;// END_INCLUDE(get_inputstream)}
private void downloadImageFromUri(String address) {URL url;try {url = new URL(address);} catch (MalformedURLException e1) {url = null;}URLConnection conn;InputStream in;Bitmap bitmap;try {conn = url.openConnection();conn.connect();in = conn.getInputStream();bitmap = BitmapFactory.decodeStream(in);in.close();} catch (IOException e) {bitmap = null;}if (bitmap != null) {ImageView img = (ImageView) findViewById(R.id.ivBasicImage);img.setImageBitmap(bitmap);}}
private void loadContacts() {Uri allContacts = Uri.parse("content://contacts/people");CursorLoader cursorLoader = new CursorLoader(this, allContacts,null, // the columns to retrivenull, // the selection criterianull, // the selection argsnull // the sort order);Cursor c = cursorLoader.loadInBackground();if (c.moveToFirst()) {do {// Get Contact IDint idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);String contactID = c.getString(idIndex);// Get Contact Nameint nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);String contactDisplayName = c.getString(nameIndex);names.add(contactDisplayName);Log.d("debug", contactID + ", " + contactDisplayName);} while (c.moveToNext());}}
TextView textView = (TextView) findViewById(R.id.test);textView.setText(text);int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);textView.measure(spec, spec);// getMeasuredWidthint measuredWidth = textView.getMeasuredWidth();// new textpaint measureTextTextPaint newPaint = new TextPaint();float textSize = getResources().getDisplayMetrics().scaledDensity * 15;newPaint.setTextSize(textSize);float newPaintWidth = newPaint.measureText(text);// textView getPaint measureTextTextPaint textPaint = textView.getPaint();float textPaintWidth = textPaint.measureText(text);
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),System.currentTimeMillis());Intent notificationIntent = new Intent(this, ExampleActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);notification.setLatestEventInfo(this, getText(R.string.notification_title),getText(R.string.notification_message), pendingIntent);startForeground(ONGOING_NOTIFICATION_ID, notification);
private class TaskSeven extends AsyncTask<Void, Integer, Void> {int mValue = 0;@Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);mTaskSevenPb.setProgress(mValue); //关键}@Overrideprotected Void doInBackground(Void... params) {while (mValue < 100) {mValue += 20;publishProgress(mValue); //关键try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}return null;}@Overrideprotected void onPostExecute(Void aVoid) {mSevenTv.setText("Over");Toast.makeText(getApplicationContext(),"TaskFour Ok",Toast.LENGTH_SHORT).show();}}
private static SharedPreferences mMusicSP;public static final String MUSIC_SP_KEY = "musicUrl";public static final String MUSIC_SP_DEFAULT = "noUrl";public static boolean saveMusicUrlByPf(Context context,String url) {mMusicSP = context.getSharedPreferences(context.getResources().getString(R.string.share_preferences_key),Context.MODE_PRIVATE);SharedPreferences.Editor editor = mMusicSP.edit();editor.putString(MUSIC_SP_KEY,url);editor.commit();return true;}public static String getMusicUrlByPf(Context context) {mMusicSP = context.getSharedPreferences(context.getResources().getString(R.string.share_preferences_key),Context.MODE_PRIVATE);String tempUrl = mMusicSP.getString(MUSIC_SP_KEY,MUSIC_SP_DEFAULT);return tempUrl;}
@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK) {if ((System.currentTimeMillis() - mBackKeyTime) > 2000) {mBackKeyTime = System.currentTimeMillis();Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();} else {finish();}}return true;}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);imm.showSoftInput(view,InputMethodManager.SHOW_FORCED); //显示imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
TextView t1 = (TextView)findViewById(R.id.txtOne);String s1 = "<font color='blue'><b>百度一下,你就知道~:</b></font><br>";s1 += "<a href = 'http://www.baidu.com'>百度</a>";t1.setText(Html.fromHtml(s1));t1.setMovementMethod(LinkMovementMethod.getInstance());
public final static String[] DEFAULT_SECTIONS = "常用 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split(" ");
private boolean validEmail(String email){Pattern emailPattern=Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");Matcher emailMatcher=emailPattern.matcher(email);return emailMatcher.matches();}
Uri smsToUri = Uri.parse( "smsto:" ); // This ensures only SMS apps respondIntent intent = new Intent(Intent.ACTION_SENDTO , smsToUri);intent.putExtra("sms_body", message);intent.putExtra("address", phoneNumber);if (intent.resolveActivity(getPackageManager()) != null) {startActivity(intent);}
overridePendingTransition(SLIDE_UP_IN, SLIDE_DOWN_OUT);
Activity的切换动画指的是从一个activity跳转到另外一个activity时的动画。用2个xml来传递参数,anim下
Intent intent = new Intent(mContext, MainActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);startActivity(intent);
int alwaysFinish = Settings.Global.getInt(getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0);if (alwaysFinish == 1) {Dialog dialog = null;dialog = new AlertDialog.Builder(this).setMessage("由于您已开启'不保留活动',导致部分功能无法正常使用.我们建议您点击左下方'设置'按钮,在'开发者选项'中关闭'不保留活动'功能.").setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).setPositiveButton("设置", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);startActivity(intent);}}).create();dialog.show();}
public class Util {private static Toast toast;public static void showToast(Context context,String content) {if (toast == null) {toast = Toast.makeText(context,content,Toast.LENGTH_SHORT);} else {toast.setText(content);}toast.show();}}