- String status=Environment.getExternalStorageState();
- if(status.equals(Enviroment.MEDIA_MOUNTED))
- {
- 说明有SD卡插入
- }
OnCreate中不设Layout this.setTheme(R.style.Theme_Transparent);
以下是Theme_Transparent的定义(注意transparent_bg是一副透明的图片)
3:在屏幕元素中设置句柄
使用Activity.findViewById来取得屏幕上的元素的句柄. 使用该句柄您可以设置或获取任何该对象外露的值.
- TextView msgTextView = (TextView)findViewById(R.id.msg);
- msgTextView.setText(R.string.push_me);
- String body=”this is mms demo”;
- Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”smsto”, number, null));
- mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
- mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);
- mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);
- startActivity(mmsintent);
5:发送彩信
- StringBuilder sb = new StringBuilder();
- sb.append(”file://”);
- sb.append(fd.getAbsoluteFile());
- Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number, null));
- // Below extra datas are all optional.
- intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
- intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
- intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
- intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
- intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
- startActivity(intent)
6:发送Mail
- mime = “img/jpg”;
- shareIntent.setDataAndType(Uri.fromFile(fd), mime);
- shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));
- shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
- shareIntent.putExtra(Intent.EXTRA_TEXT, body);
7:注册一个BroadcastReceiver
- registerReceiver(mMasterResetReciever, new IntentFilter(”oms.action.MASTERRESET”));
- private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent){
- String action = intent.getAction();
- if(”oms.action.MASTERRESET”.equals(action)){
- RecoverDefaultConfig();
- }
- }
- }
8:定义ContentObserver,监听某个数据表
- private ContentObserver mDownloadsObserver = new DownloadsChangeObserver(Downloads.CONTENT_URI);
- private class DownloadsChangeObserver extends ContentObserver {
- public DownloadsChangeObserver(Uri uri) {
- super(new Handler());
- }
- @Override
- public void onChange(boolean selfChange) {}
- }
9:获得 手机UA
- public String getUserAgent()
- {
- String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
- return user_agent;
- }
10:清空手机上Cookie
- CookieSyncManager.createInstance(getApplicationContext());
- CookieManager.getInstance().removeAllCookie();
- //Dial the GPRS link.
- private boolean openDataConnection() {
- // Set up data connection.
- DataConnection conn = DataConnection.getInstance();
- if (connectMode == 0) {
- ret = conn.openConnection(mContext, “cmwap”, “cmwap”, “cmwap”);
- } else {
- ret = conn.openConnection(mContext, “cmnet”, “”, “”);
- }
- }
12:PreferenceActivity 用法
- public class Setting extends PreferenceActivity
- {
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- addPreferencesFromResource(R.xml.settings);
- }
- }
- Setting.xml:
- android:key=”seting2″
- android:title=”@string/seting2″
- android:summary=”@string/seting2″/>
- android:key=”seting1″
- android:title=”@string/seting1″
- android:summaryOff=”@string/seting1summaryOff”
- android:summaryOn=”@stringseting1summaryOff”/>
13:通过HttpClient从指定server获取数据
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpGet method = new HttpGet(“http://www.baidu.com/1.html”);
- HttpResponse resp;
- Reader reader = null;
- try {
- // AllClientPNames.TIMEOUT
- HttpParams params = new BasicHttpParams();
- params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
- httpClient.setParams(params);
- resp = httpClient.execute(method);
- int status = resp.getStatusLine().getStatusCode();
- if (status != HttpStatus.SC_OK) return false;
- // HttpStatus.SC_OK;
- return true;
- } catch (ClientProtocolException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (reader != null) try {
- reader.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- DisplayMetrics dm = new DisplayMereics();
- getWindowManager().getDefaultDisplay().getMetrics(dm);
- float width = dm.widthPixels * dm.density;
- float height = dm.heightPixels * dm.density
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.mainlay);
- mediaPlayer = MediaPlayer.create(this, R.raw.mu);
- mediaPlayer.setLooping(true);
- mediaPlayer.start();
- }
16、让程序的界面不随机器的重力感应而翻转
第一种方法,在manifast文件里面
- <activity
- android:screenOrientation="portrait">
- </activity>
第二种,在代码里面
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
17、使activity全屏显示
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
- WindowManager.LayoutParams. FLAG_FULLSCREEN);
18、在RelativeLayout中使selector要注意点
关于selector的使用方法,可以参考http://blog.csdn.net/aomandeshangxiao/article/details/6759576这篇文章,今天,遇到在RelativeLayout中添加background为selector后没有反应的问题,寻摸了很长时间,一直没有找到原因,其实只要加上一句代码就完全可以解决:
- <span style="font-size:16px;">RelativeLayout 里面加上android:clickable="true"</span>
这样,RelativLayout就会出现在selector里面定义的效果。
19、显示或隐藏虚拟键盘
- 显示:
- InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
- imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
- 隐藏:
- InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
- imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);
20、退出程序时清除通知中信息
- NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- nm.cancelAll();
21、创建快捷方式
- Intent intent=new Intent();
- //设置快捷方式的图标
- intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));
- //设置快捷方法的名称
- intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "点击启动哥的程序"); //设置点击快键图标的响应操作
- intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));
- //传递Intent对象给系统
- setResult(RESULT_OK, intent);
- finish();
22、获取文件中的类名:
- String path = context.getPackageManager().getApplicationInfo(
- context.getPackageName(), 0).sourceDir;
- DexFile dexfile = new DexFile(path);
- Enumeration<String> entries = dexfile.entries();
- while (entries.hasMoreElements()) {
- String name = (String) entries.nextElement();
- ......
- }
23. TextView中的getTextSize返回值是以像素(px)为单位的,
而setTextSize()是以sp为单位的.
所以如果直接用返回的值来设置会出错,解决办法是:
用setTextSize()的另外一种形式,可以指定单位:
- TypedValue.COMPLEX_UNIT_PX : Pixels
- TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
- TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
- TypedValue.COMPLEX_UNIT_PX : Pixels
- TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
- TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
24. 在继承自View时,绘制bitmap时,需要将图片放到新建的drawable-xdpi
中,否则容易出现绘制大小发生改变
25. 在文字中加下划线: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
26. scrollView是继承自frameLayout,所以在使用LayoutParams时需要用frameLayout的
27、android阴影字体设置
- <TextView android:id="@+id/tvText1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="text1"
- android:textSize="30sp"
- android:textStyle="bold"
- android:textColor="#FFFFFF"
- android:shadowColor="#ff0000ff"
- android:shadowDx="5"
- android:shadowDy="5"
- android:shadowRadius="10"/>
android:shadowColor 阴影颜色
android:shadowDx 阴影的水平偏移量
android:shadowDy 阴影的垂直偏移量
android:shadowRadius 阴影的范围
为了统一风格和代码的复用,通常可以把这个样式抽取放入到style.xml文件中
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <style name="textstyle">
- <item name="android:shadowColor">#ff0000ff</item>
- <item name="android:shadowRadius">10</item>
- <item name="android:shadowDx">5</item>
- <item name="android:shadowDy">5</item>
- </style>
- </resources>
- <TextView
- style="@style/textstyle"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="字体样式"
- android:textSize="30sp"
- android:textStyle="bold" />
28、android实现手机震动功能
- import android.app.Activity;
- import android.app.Service;
- import android.os.Vibrator;
- public class TipHelper {
- public static void Vibrate(final Activity activity, long milliseconds) {
- Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
- vib.vibrate(milliseconds);
- }
- public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {
- Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
- vib.vibrate(pattern, isRepeat ? 1 : -1);
- }
- }
- <uses-permission android:name="android.permission.VIBRATE" />
final Activity activity :调用该方法的Activity实例
long milliseconds :震动的时长,单位是毫秒
long[] pattern :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒
boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次
29、常用的正则表达式
^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$ //email地址
^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$ //url
^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0|1]))$ //年-月-日
^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$ //月/日/年
^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$ //Emil
^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$ //电话号码
^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$ //IP地址
(^\s*)|(\s*$) // 首尾空格
^[a-zA-Z][a-zA-Z0-9_]{4,15}$ // 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)
^[1-9]*[1-9][0-9]*$ // 腾讯QQ号
30、输入框不挤压activity布局:
在manifest文件activity下 加:
- android:windowSoftInputMode="adjustPan"
31、listview中item中button可点击:
- android:descendantFocusability="blocksDescendants"
32、获取移动设备的IP地址:
- public class Tools {
- public static String getLocalIpAddress() {
- try {
- for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
- NetworkInterface intf = en.nextElement();
- for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
- InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress()) {
- return inetAddress.getHostAddress().toString();
- }
- }
- }
- } catch (SocketException ex) {
- Log.e("出错啦", ex.toString());
- }
- return null;
- }
- }
- 然后
- WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
- WifiInfo wi = wm.getConnectionInfo();
- System.out.println("IP地址是:"+Tools.getLocalIpAddress());
- System.out.println("SSID:"+wi.getSSID());
- 最后记得加两个权限
- <uses-permission android:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
33、高仿小米launcher跨屏拖动item(GridView长按item进行拖动
触发长按事件后浮动原理:
- windowParams = new WindowManager.LayoutParams();
- windowParams.gravity = Gravity.TOP | Gravity.LEFT;
- windowParams.x = x - itemWidth / 2;
- windowParams.y = y - itemHeight / 2;
- windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
- windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
- ImageView iv = new ImageView(getContext());
- iv.setImageBitmap(bm);
- windowManager = (WindowManager) getContext().getSystemService(
- Context.WINDOW_SERVICE);// "window"
- windowManager.addView(iv, windowParams);
- if (dragImageView != null) {
- windowParams.alpha = 0.6f;
- windowParams.x = x - itemWidth / 2;
- windowParams.y = y - itemHeight / 2;
- windowManager.updateViewLayout(dragImageView, windowParams);
- }