[关闭]
@ZeroGeek 2016-08-03T01:33:15.000000Z 字数 7101 阅读 692

Android部分实用代码整理

android


读取字符串

  1. private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
  2. Reader reader = null;
  3. reader = new InputStreamReader(stream, "UTF-8");
  4. char[] buffer = new char[len];
  5. reader.read(buffer);
  6. return new String(buffer);
  7. }

网络下载

  1. private InputStream downloadUrl(String urlString) throws IOException {
  2. // BEGIN_INCLUDE(get_inputstream)
  3. URL url = new URL(urlString);
  4. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  5. conn.setReadTimeout(10000 /* milliseconds */);
  6. conn.setConnectTimeout(15000 /* milliseconds */);
  7. conn.setRequestMethod("GET");
  8. conn.setDoInput(true);
  9. // Start the query
  10. conn.connect();
  11. InputStream stream = conn.getInputStream();
  12. return stream;
  13. // END_INCLUDE(get_inputstream)
  14. }

图片下载

  1. private void downloadImageFromUri(String address) {
  2. URL url;
  3. try {
  4. url = new URL(address);
  5. } catch (MalformedURLException e1) {
  6. url = null;
  7. }
  8. URLConnection conn;
  9. InputStream in;
  10. Bitmap bitmap;
  11. try {
  12. conn = url.openConnection();
  13. conn.connect();
  14. in = conn.getInputStream();
  15. bitmap = BitmapFactory.decodeStream(in);
  16. in.close();
  17. } catch (IOException e) {
  18. bitmap = null;
  19. }
  20. if (bitmap != null) {
  21. ImageView img = (ImageView) findViewById(R.id.ivBasicImage);
  22. img.setImageBitmap(bitmap);
  23. }
  24. }

读取联系人

  1. private void loadContacts() {
  2. Uri allContacts = Uri.parse("content://contacts/people");
  3. CursorLoader cursorLoader = new CursorLoader(this, allContacts,
  4. null, // the columns to retrive
  5. null, // the selection criteria
  6. null, // the selection args
  7. null // the sort order
  8. );
  9. Cursor c = cursorLoader.loadInBackground();
  10. if (c.moveToFirst()) {
  11. do {
  12. // Get Contact ID
  13. int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
  14. String contactID = c.getString(idIndex);
  15. // Get Contact Name
  16. int nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
  17. String contactDisplayName = c.getString(nameIndex);
  18. names.add(contactDisplayName);
  19. Log.d("debug", contactID + ", " + contactDisplayName);
  20. } while (c.moveToNext());
  21. }
  22. }

获取TextView显示的字符串宽度

  1. TextView textView = (TextView) findViewById(R.id.test);
  2. textView.setText(text);
  3. int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
  4. textView.measure(spec, spec);
  5. // getMeasuredWidth
  6. int measuredWidth = textView.getMeasuredWidth();
  7. // new textpaint measureText
  8. TextPaint newPaint = new TextPaint();
  9. float textSize = getResources().getDisplayMetrics().scaledDensity * 15;
  10. newPaint.setTextSize(textSize);
  11. float newPaintWidth = newPaint.measureText(text);
  12. // textView getPaint measureText
  13. TextPaint textPaint = textView.getPaint();
  14. float textPaintWidth = textPaint.measureText(text);

Service中显示Status Bar Notifications

  1. Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
  2. System.currentTimeMillis());
  3. Intent notificationIntent = new Intent(this, ExampleActivity.class);
  4. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
  5. notification.setLatestEventInfo(this, getText(R.string.notification_title),
  6. getText(R.string.notification_message), pendingIntent);
  7. startForeground(ONGOING_NOTIFICATION_ID, notification);

结合AsyncTask与ProgressBar

  1. private class TaskSeven extends AsyncTask<Void, Integer, Void> {
  2. int mValue = 0;
  3. @Override
  4. protected void onProgressUpdate(Integer... values) {
  5. super.onProgressUpdate(values);
  6. mTaskSevenPb.setProgress(mValue); //关键
  7. }
  8. @Override
  9. protected Void doInBackground(Void... params) {
  10. while (mValue < 100) {
  11. mValue += 20;
  12. publishProgress(mValue); //关键
  13. try {
  14. Thread.sleep(1000);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. return null;
  20. }
  21. @Override
  22. protected void onPostExecute(Void aVoid) {
  23. mSevenTv.setText("Over");
  24. Toast.makeText(getApplicationContext(),"TaskFour Ok",Toast.LENGTH_SHORT).show();
  25. }
  26. }

运用SharePreference存储和读区(注意权限)

  1. private static SharedPreferences mMusicSP;
  2. public static final String MUSIC_SP_KEY = "musicUrl";
  3. public static final String MUSIC_SP_DEFAULT = "noUrl";
  4. public static boolean saveMusicUrlByPf(Context context,String url) {
  5. mMusicSP = context.getSharedPreferences(context.getResources().getString(R.string.share_preferences_key)
  6. ,Context.MODE_PRIVATE);
  7. SharedPreferences.Editor editor = mMusicSP.edit();
  8. editor.putString(MUSIC_SP_KEY,url);
  9. editor.commit();
  10. return true;
  11. }
  12. public static String getMusicUrlByPf(Context context) {
  13. mMusicSP = context.getSharedPreferences(context.getResources().getString(R.string.share_preferences_key)
  14. ,Context.MODE_PRIVATE);
  15. String tempUrl = mMusicSP.getString(MUSIC_SP_KEY,MUSIC_SP_DEFAULT);
  16. return tempUrl;
  17. }

按2次返回键退出程序

  1. @Override
  2. public boolean onKeyDown(int keyCode, KeyEvent event) {
  3. if(keyCode == KeyEvent.KEYCODE_BACK) {
  4. if ((System.currentTimeMillis() - mBackKeyTime) > 2000) {
  5. mBackKeyTime = System.currentTimeMillis();
  6. Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
  7. } else {
  8. finish();
  9. }
  10. }
  11. return true;
  12. }

显示/隐藏软件盘

  1. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  2. imm.showSoftInput(view,InputMethodManager.SHOW_FORCED); //显示
  3. imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘

使背景模糊,用于启动的Tips

  1. getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
  2. WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

TextView使用技巧

  1. TextView t1 = (TextView)findViewById(R.id.txtOne);
  2. String s1 = "<font color='blue'><b>百度一下,你就知道~:</b></font><br>";
  3. s1 += "<a href = 'http://www.baidu.com'>百度</a>";
  4. t1.setText(Html.fromHtml(s1));
  5. t1.setMovementMethod(LinkMovementMethod.getInstance());

巧用String分割

  1. 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(" ");

验证邮箱

  1. private boolean validEmail(String email){
  2. Pattern emailPattern=Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
  3. Matcher emailMatcher=emailPattern.matcher(email);
  4. return emailMatcher.matches();
  5. }

调用系统接口发送短信

  1. Uri smsToUri = Uri.parse( "smsto:" ); // This ensures only SMS apps respond
  2. Intent intent = new Intent(Intent.ACTION_SENDTO , smsToUri);
  3. intent.putExtra("sms_body", message);
  4. intent.putExtra("address", phoneNumber);
  5. if (intent.resolveActivity(getPackageManager()) != null) {
  6. startActivity(intent);
  7. }

Activity的切换动画

  1. overridePendingTransition(SLIDE_UP_IN, SLIDE_DOWN_OUT);

Activity的切换动画指的是从一个activity跳转到另外一个activity时的动画。用2个xml来传递参数,anim下

设置FLAG_ACTIVITY_CLEAR_TOP来清除历史栈

  1. Intent intent = new Intent(mContext, MainActivity.class);
  2. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  3. startActivity(intent);

提醒是否关闭开发者不保留活动

  1. int alwaysFinish = Settings.Global.getInt(getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0);
  2. if (alwaysFinish == 1) {
  3. Dialog dialog = null;
  4. dialog = new AlertDialog.Builder(this)
  5. .setMessage(
  6. "由于您已开启'不保留活动',导致部分功能无法正常使用.我们建议您点击左下方'设置'按钮,在'开发者选项'中关闭'不保留活动'功能.")
  7. .setNegativeButton("取消", new DialogInterface.OnClickListener() {
  8. @Override
  9. public void onClick(DialogInterface dialog, int which) {
  10. dialog.dismiss();
  11. }
  12. }).setPositiveButton("设置", new DialogInterface.OnClickListener() {
  13. @Override
  14. public void onClick(DialogInterface dialog, int which) {
  15. Intent intent = new Intent(
  16. Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
  17. startActivity(intent);
  18. }
  19. }).create();
  20. dialog.show();
  21. }

Toast的最佳使用

  1. public class Util {
  2. private static Toast toast;
  3. public static void showToast(Context context,
  4. String content) {
  5. if (toast == null) {
  6. toast = Toast.makeText(context,
  7. content,
  8. Toast.LENGTH_SHORT);
  9. } else {
  10. toast.setText(content);
  11. }
  12. toast.show();
  13. }
  14. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注