Android学习笔记-常用的一些源码,防止忘记了。。。

http://blog.csdn.net/yao_guet/article/details/6289185

Android 学习笔记


1.

长点击控件菜单,即我们常说的右键菜单,不过好像ContextMenu不支持ICON的,
所以即使在源码里面可以使用setIcon函数,但是还是不会有效果的。。。
一般有下面三个步骤:
// 通常在onCreate函数中注册一个控件,btn为需要弹出ContextMenu的控件
this.registerForContextMenu(btn);
///
// 下面函数是创建ContextMenu的,v是被点击的控件
// 根据v进行判断可以对不同的控件,创建不同的ContextMenu
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo)
///
// 下面函数是响应ContextMenu点击事情的。。
public boolean onContextItemSelected(MenuItem item)


2.
Toast显示信息,可以方便的来输出信息
Toast.makeText(this, "Info", Toast.LENGTH_LONG).show();


3.
关于MENU的操作
有两个比较重要的了,函数原型:
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title);
public abstract SubMenu addSubMenu (CharSequence title);
一般的函数有:
menu.setHeaderTitle("MenuTitle");
menu.setHeaderIcon(R.drawable.icon);
menu.add(0, 0, 0, "item0").setIcon(R.drawable.icon);
menu.add(0, 1, 1, "item1");
///
SubMenu sub = menu.addSubMenu("SubMenu");
sub.add(0, 5, 5, "item5");
sub.add(0, 6, 6, "item6");



4.
获取屏幕的分辨率
isplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
dm.widthPixels
dm.heightPixels


5.
显示POPUP对话框,类似于Windows的MessageBox函数,不过这个要比MessageBox强大多了,,,
可以设置单选或者多选项,以及其响应,有两种方法可以
一:
实现Activity的onCreateDialog函数。
showDialog(ID_TEST_DIALOG);
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case ID_TEST_DIALOG:
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("AlertDialog Test")
.setMessage("This is a test for AlertDialg!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
})
.create();
return dialog;
default:
break;
}
return super.onCreateDialog(id);
}
这里有个配套的函数
dismissDialog(D_TEST_DIALOG);
这个可以关闭相应的Dialog.
///
二:
直接调用Builder函数去完成创建与显示。
new AlertDialog.Builder(this)
.setTitle("AlertDialog Test")
.setMessage("This is a test for AlertDialg!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
})
.show();


6.
从一个xml布局获取其View的方法。
这个好像有两种方法,不过都是得到一个LayoutInflater之后再inflate得到指定xml布局相对应的View.
一:
LayoutInflater li;
li = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.la_test, null);
二:
LayoutInflater li;
li = LayoutInflater.from(this);
View v = li.inflate(R.layout.la_test, null);


7.
知道第二个方法和第六个方法之后,我们可以把这两个方法综合起来。
就是可以自定义的显示一段时间的图形,这个说法有点抽象,简单一点就是做一个类似音量调节那样的浮动窗口。
思路是这样的,可以新建一个Toast,然后再inflate一个布局,设置里面的内容,然后再把内容放到Toast里面显示
LayoutInflater li;
li = LayoutInflater.from(this);
View v = li.inflate(R.layout.la_test, null);
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(v);
toast.show();


8.
当按返回键时,完全按退出系统
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}


9.
获取状态栏和标题栏的高度
获取状态栏高度: 
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。 
于是,我们就可以算出状态栏的高度了。
Rect frame = new Rect();  
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
int statusBarHeight = frame.top; 
获取标题栏高度: 
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。 
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
//statusBarHeight是上面所求的状态栏的高度  
int titleBarHeight = contentTop - statusBarHeight  


10.
关于窗口的一些操作
不显示标题栏
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
或者是设置一个style属性,主题,加入下面的项
<item name="android:windowNoTitle">true</item>

设置背景半暗
LayoutParams lp = getWindow().getAttributes();
lp.dimAmount = 0.5f;
// 设置透明度是alpha的值
// lp.alpha = 0.8f;
getWindow().setAttributes(lp);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

设置背景模糊
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

一般可能有用的style设置,以防以后忘记了,,,
<item name="android:windowBackground">@drawable/color_translucent</item>
<item name="android:windowIsTranslucent">true</item>


11.
获取SD卡总空间和可用空间
public static String getSDcardStorage() {
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File sdcardDir = Environment.getExternalStorageDirectory();
   StatFs sf = new StatFs(sdcardDir.getPath());
   long blockSize = sf.getBlockSize();
   long blockCount = sf.getBlockCount();
   long availCount = sf.getAvailableBlocks();
   return "SD卡:" + formatSize(blockSize*blockCount)
    + " 可用空间:" + formatSize(availCount*blockCount);
}
return null;
}

获取系统空间和可用空间
public static String getSystemStorage() {
File root = Environment.getRootDirectory();   
        StatFs sf = new  StatFs(root.getPath());   
        long  blockSize = sf.getBlockSize();   
        long  blockCount = sf.getBlockCount();   
        long  availCount = sf.getAvailableBlocks();   
        return "总空间:" + formatSize(blockSize*blockCount)
     + " 可用空间:" + formatSize(availCount*blockSize);
    } 



12.
在资源文件中使用Android定义的资源的方法
在Android系统中定义了很多动画与样式,我们可能在eclipse开发程序的时候使用系统定义的资源,
哈哈,这样可以保持与系统显示的样式一致~~~
对于定义为:android.R.drawable.status_bar_item_background的样式,
只需在eclipse的资源文件中写为:@android:drawable/status_bar_item_background
总结一下,所以可以写为下面的样子。。。
android:background="@android:drawable/status_bar_item_background"


13.
Android.mk文件的说明。
JAR: include $(BUILD_JAVA_LIBRARY),源文件为java
SO:include $(BUILD_SHARED_LIBRARY),源文件为 c或c++
APK:include $(BUILD_PACKAGE),源文件为java
二进制可执行文件:include $(BUILD_EXECUTABLE),源文件为c或c++

如需要在java文件中调用so文件,如:libabc.so则需在Android.mk文件中添加:
LOCAL_JNI_SHARED_LIBRARIES := libabc
同时,需要在java文件中System.loadLibrary("abc");,注意此时不需要在加上lib前缀


14.
模拟按键消息
private void sendVKeyDelay(int key) {
final int keyCode = key;
Thread sendKeyDelay = new Thread(){
public void run() {
try {
Thread.sleep(100);

long now = SystemClock.uptimeMillis();
KeyEvent keyDown = new KeyEvent(now, now, KeyEvent.ACTION_DOWN,
keyCode, 0);
IWindowManager wm = IWindowManager.Stub.asInterface(
ServiceManager.getService("window"));
wm.injectKeyEvent(keyDown, false);

KeyEvent keyUp = new KeyEvent(now, now, KeyEvent.ACTION_UP,
keyCode, 0);
wm.injectKeyEvent(keyUp, false);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
sendKeyDelay.start();
}


15.
使用startActivity应该注意的异常,处理各种情况跟异常!!!
    void startActivitySafely(Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
            e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
                    "or use the exported attribute for this activity.", e);
        }
    }


16.
创建动画效果。
public void createAnimation() {
if (mInAnimation == null) {
mInAnimation  = new AnimationSet(false);
final AnimationSet ani = mInAnimation;
ani.setInterpolator(new AnticipateOvershootInterpolator(2.5f));
ani.addAnimation(new AlphaAnimation(0.0f, 1.0f));
ani.addAnimation(new TranslateAnimation(Animation.ABSOLUTE, 0.0f, 
Animation.ABSOLUTE, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
Animation.RELATIVE_TO_SELF, 0.0f));
ani.setDuration(1000);
}
if (mOutAnimation == null) {
mOutAnimation = new AnimationSet(false);
AnimationSet ano = mOutAnimation;
ano.setInterpolator(new AnticipateOvershootInterpolator(2.5f));
ano.addAnimation(new AlphaAnimation(1.0f, 0.0f));
ano.addAnimation(new TranslateAnimation(Animation.ABSOLUTE, 0.0f, 
Animation.ABSOLUTE, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f));
ano.setDuration(1000);
}
}


17.
显示一个浮动的窗口(任意View).
mWindowManager = (WindowManager)getSystemService(
Context.WINDOW_SERVICE);
mDialog = LayoutInflater.from(mContext).inflate(
R.layout.popup, null);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
(int)event.getX(), (int)event.getY(),
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.TOP | Gravity.LEFT;
mWindowManager.addView(mDialog, lp);
如果需要隐藏,则remove即可
mWindowManager.removeView(mDialog);


18.
设置应用程序全屏显示
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);


19.
获取系统所有的安装程序
final PackageManager packageManager = getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);


20.
手机振动,代码片段。
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, -1);
需要在AndroidManifest.xml文件添加权限
<uses-permission android:name="android.permission.VIBRATE" />


21.
设置开机运行程序,需要在AndroidManifest.xml中添加
<intent-filter>
<!-- 系统启动完成后会调用-->
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>


22.
简单的使用ListView的方法,
一,单行文字的
List<String> list = new ArrayList<String>();
lvData.setAdapter(new ArrayAdapter(this, 
android.R.layout.simple_list_item_1, list));
二,双行文字,使用SimpleAdapter
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", cursor.getString(0));
map.put("UserName", cursor.getString(1));
list.add(map);
lvData.setAdapter(new SimpleAdapter(this, list, 
android.R.layout.simple_expandable_list_item_2, 
new String[]{"ID","UserName"},
new int[]{android.R.id.text1, android.R.id.text2}));


23.
SQLiteDatabase中模拟使用Truncate方法清空数据表跟计数器的方法
先使用"DELETE FROM TableName"语句清空数据表数据
再使用"UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME=\"TableName\""置0计数器
下面是清空表“Users”
try {
mDatabase.execSQL("DELETE FROM Users");
mDatabase.execSQL("update sqlite_sequence set seq=0 where name=\"Users\"");
} catch (SQLException se) {
Toast.makeText(this, se.getMessage(), Toast.LENGTH_LONG).show();
se.printStackTrace();
}


24.
使用ADB以可读写方式重新挂载根目录,可以读写sbin文件夹
./adb shell
su
mount -o remount,rw dev/block/mtdblock3 /


25.
android中通过代码实现文件权限修改
try {
String command = "chmod 777 " + destFile.getAbsolutePath();
Log.i("zyl", "command = " + command);
Runtime runtime = Runtime.getRuntime(); 
Process proc = runtime.exec(command);
} catch (IOException e) {
Log.i("zyl","chmod fail!!!!");
e.printStackTrace();
}


26.
Android 隐藏应用程序图标
把<category android:name="android.intent.category.LAUNCHER" />删除即可


27.
使用Tab分页内容。
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        TabHost mTabHost = this.getTabHost();
        
        Intent intent = new Intent(this, TabContent.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra("Yao.GUET", 0);
        mTabHost.addTab(mTabHost.newTabSpec("Tab_1")
         .setIndicator("Tab 1", 
         getResources().getDrawable(R.drawable.icon))
         .setContent(intent));
        
        Intent intent2 = new Intent(this, TabContent.class);
        intent2.setAction(Intent.ACTION_VIEW);
        intent2.putExtra("Yao.GUET", 1);
        mTabHost.addTab(mTabHost.newTabSpec("Tab_2")
         .setIndicator("Tab 2", 
         getResources().getDrawable(R.drawable.icon))
         .setContent(intent2));
        
        mTabHost.setCurrentTab(0);
    }


28.
设置透明背景,修改AndroidManifest.xml文件,在对应的Activity里面加上下面的属性:
android:theme="@android:style/Theme.Translucent"
使用系统背景作为应用的背景,在onCreate的时候添加窗口标志:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);


29.
播放系统铃声代码
// play the notification sound...
private void playNotifySound(Context context) {
Uri Notify_Sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, Notify_Sound);
final AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mMediaPlayer.setLooping(false);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


30.

打印当前函数的系统调用堆栈

java.util.Map<Thread, StackTraceElement[]> ts = Thread.getAllStackTraces();  
StackTraceElement[] ste = ts.get(Thread.currentThread());  
for (StackTraceElement s : ste) {  
    Log.i(TAG, "StackTraceElement  :"+s.toString()); 
}  


31.

获取当前函数的函数名称

Thread.currentThread().getStackTrace()[2].getMethodName();


32.

往手机发送一个按键消息,event号可能按手机而不一样,第一个1是表示按键事件,139是键值,后面的数值1表示down,0表示up

adb shell sendevent /dev/input/event1 1 139 1 && adb shell sendevent /dev/input/event1 1 139 0


33.

指定使用finger layout,AndroidManifest.xml
<uses-configuration android:reqTouchScreen="finger" />


34.

设置某activity只能有一个实例

<activity android:name=".TTSActivity"
                  android:label="@string/app_name"
                  android:launchMode="singleTask">


35.

使用adb shell启动一个activity. -n 后面跟着的是包名/.需要启动的类名

adb shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -n com.android.contacts/.DialtactsContactsEntryActivity -f 0x10200000


36.
增大SD卡的读写缓存,以KB为单位,下面设置2048KB
echo "2048" > /sys/devices/virtual/bdi/179\:0/read_ahead_kb


37.

java获取当前时间的字符串

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
String str =  format.format(new java.util.Date());



  有时候,需要一些小的功能,找到以后,就把它贴到了博客下面,作为留言,查找起来很不方便,所以就整理一下,方便自己和他人。

         一、  获取系统版本号:

[java]  view plain copy
  1. PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);  
  2. int versionCode=nfo.versionCode  
  3. string versionName=info.versionNam  

              二、获取系统信息:

[java]  view plain copy
  1. <span style="font-size:16px;">String archiveFilePath="sdcard/download/Law.apk";//安装包路径  
  2. PackageManager pm = getPackageManager();   
  3. PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);   
  4. if(info != null){   
  5. ApplicationInfo appInfo = info.applicationInfo;   
  6. String appName = pm.getApplicationLabel(appInfo).toString();   
  7. String packageName = appInfo.packageName; //得到安装包名称  
  8. String version=info.versionName; //得到版本信息   
  9. Toast.makeText(test4.this"packageName:"+packageName+";version:"+version, Toast.LENGTH_LONG).show();  
  10. Drawable icon = pm.getApplicationIcon(appInfo);//得到图标信息  
  11. TextView tv = (TextView)findViewById(R.id.tv); //显示图标  
  12. tv.setBackgroundDrawable(icon);</span>  

        三、获取安装路径和已安装程序列表

[java]  view plain copy
  1. <span style="font-size:16px;">(1)android中获取当前程序路径  
  2. getApplicationContext().getFilesDir().getAbsolutePath()  
  3. (2)android取已安装的程序列表  
  4. List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages(0);</span>  

       四、获取图片、应用名、包名

[java]  view plain copy
  1. <span style="font-size:16px;">PackageManager pManager = MessageSendActivity.this.getPackageManager();   
  2. List<PackageInfo> appList = Utils.getAllApps(MessageSendActivity.this);   
  3.      for(int i=0;i<appList.size();i++) {   
  4.          PackageInfo pinfo = appList.get(i);   
  5.          ShareItemInfo shareItem = new ShareItemInfo();   
  6.          //set Icon   
  7.          shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo));   
  8.          //set Application Name shareItem.setLabel(pManager.getApplicationLabel(pinfo.applicationInfo).toString());   
  9.         //set Package Name shareItem.setPackageName(pinfo.applicationInfo.packageName);   
  10. }</span>  
         五、解决listview上 Item上有按钮时 item本身不能点击的问题:

[java]  view plain copy
  1. <span style="font-size:16px;">1. 在item试图上面添加代码: android:descendantFocusability="blocksDescendants"  
  2. 2.在listview里 添加代码 android:focusable="true"</span>  
         六、不让文本框输入中文:

[html]  view plain copy
  1. <span style="font-size:16px;">在xml文件里面</span>  
[html]  view plain copy
  1. <span style="font-size:16px;">android:digits="1234567890qwertyuiopasdfghjklzxcvbnm`-=[]\;,./~!@#$%^*()_+}{:?&<>"'"  
  2. 这样就不会输入中文了。  
  3. </span>  
        
         七、获取屏幕宽高

[java]  view plain copy
  1. <span style="font-size:16px;">DisplayMetrics displayMetrics = new DisplayMetrics();   
  2. this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);   
  3. int height = displayMetrics.heightPixels;   
  4. int width = displayMetrics.widthPixels;  
  5. </span>  
         八、将TabWidget显示在屏幕下方

[java]  view plain copy
  1. <span style="font-size:16px;">设置TabWidget的属性 android:layout_alignParentBottom="true"</span>  
为了让tabHost显示在下方,要将RadioGroup的layout_gravity设置为bottom,再将FrameLayout的 layout_weight设置为1,这样就可以将RadioGroup撑到最下方。style="@style/main_tab_bottom"里面定义了样式文件      

         九、获取线程ID和线程名称:

[java]  view plain copy
  1. <span style="font-size:16px;">Log.v("@@@@@@@@@@",Thread.currentThread().getId()+" "+Thread.currentThread().getName());  
  2. </span>  

        十、android中调用其它android应用

[java]  view plain copy
  1. <span style="font-size:16px;">ComponentName comp = new ComponentName("com.Test","com.login.Main");   
  2.  intent = new Intent();   
  3.  intent.setComponent(comp);   
  4.  intent.setAction("android.intent.action.VIEW");   
  5.  startActivity(intent);  
  6. </span>  
         十一、禁止软键盘弹出

[java]  view plain copy
  1. <span style="font-size:16px;">EditText有焦点(focusable为true)阻止输入法弹出 editText.setInputType(InputType.TYPE_NULL); // 关闭软键盘   
  2. 当EidtText无焦点(focusable=false)时阻止输入法弹出   
  3.   
  4. InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);   
  5. imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);  
  6. </span>  
【Android】EditText标签调用键盘
在xml文件中EditText标签有一个属性android:editable="false"和android:numeric="integer"

android:numeric="integer"表示只允许输入数字,此属性可以限制用户只能输入数字内容。
android:editable表示是否可以输入内容TRUE表示可以输入,false表示不允许输入内容;
当为android:editable="false"时,点击输入框,虚拟键盘是显示不出来的,不过当设置了 android:editable=""属性时,不管是false还是true,在其后加入android:numeric="integer"属性时,是可以输入数字内容了;这里没搞明白是怎么回事,也许是numeric把前面的属性覆盖掉了。
当android:editable="false"时,在java类里如果再规定EditText.setEnabled(true)时,虚拟键盘还是不会显示的。

       十二、模拟器的各种规格与分辨率对照:
[html]  view plain copy
  1. 单位:像素   
  2. WVGA854: 854*480  
  3. WVGA800: 800*480  
  4. HVGA: 480*320   
  5. QVGA: 320*240  
  6. WQVGA432:432*240   
  7. WQVGA400:400*240   
    
          十三、调用Android其他Context的Activity
[java]  view plain copy
  1. Context c = createPackageContext("chroya.demo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);  
  2. //载入这个类  
  3. Class clazz = c.getClassLoader().loadClass("chroya.demo.Main");  
  4. //新建一个实例  
  5. Object owner = clazz.newInstance();  
  6. //获取print方法,传入参数并执行  
  7. Object obj = clazz.getMethod("print", String.class).invoke(owner, "Hello");  
这个方法有两个参数:
1、packageName  包名,要得到Context的包名
2、 flags  标志位,有CONTEXT_INCLUDE_CODE和CONTEXT_IGNORE_SECURITY两个选项。 CONTEXT_INCLUDE_CODE的意思是包括代码,也就是说可以执行这个包里面的代码。CONTEXT_IGNORE_SECURITY的意思 是忽略安全警告,如果不加这个标志的话,有些功能是用不了的,会出现安全警告。
 
           十四、android4.0Dialog风格小技巧

4.0上如果还用Theme.Dialog,只能说很土,跟整体UI风格差别很大

请使用android:theme="@android:style/Theme.Holo.DialogWhenLarge"


   
         十五、程序中安装apk
     
[java]  view plain copy
  1. Intent intent = new Intent();             
  2.        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  3.     intent.setAction(android.content.Intent.ACTION_VIEW);  
  4.     intent.setDataAndType(Uri.fromFile(“APK”),"application/vnd.android.package-archive");  
  5.     startActivity(intent);  

其中“apk”为你要安装的那个文件。

         十六、获取设备型号、SDK版本及系统版本

[java]  view plain copy
  1. String device_model = Build.MODEL; // 设备型号    
  2. String version_sdk = Build.VERSION.SDK; // 设备SDK版本    
  3. String version_release = Build.VERSION.RELEASE; // 设备的系统版本    

            十七、图片分析功能

[java]  view plain copy
  1. public void SharePhoto(String photoUri,final Activity activity) {    
  2.     Intent shareIntent = new Intent(Intent.ACTION_SEND);    
  3.     File file = new File(photoUri);    
  4.     shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));    
  5.     shareIntent.setType("image/jpeg");    
  6.     StartActivity(Intent.createChooser(shareIntent, activity.getTitle()));    
  7. }    


         十八、linux关机命令

在Windows下,按着电源键4秒强制关机,在Linux下强烈不建议这么做。Windows由于是单用户、“假多”任务的情况,所以即使你的计算机关机,也不会对别人造成影响。不过在Linux中,由于每个程序都是在后台执行的,因此,在你看不到的屏幕背后可能有很多人同时在你的主机上工作。而且,若不正常关机可能会造成文件系统的损毁。所以,正常情况下,要关机时需要注意下面几件事情:

(1)查看系统的使用状态。

要看目前有谁在线,可以用who命令。要看网络的联机状态,可以用netstat-a命令。要看后台执行那个的程序可以执行ps-aux命令。

(2)通知在线用户的关机时刻

这个时候可以使用shutdown命令

[java]  view plain copy
  1. Shutdown命令:  
  2. 语法:shutdown[-t秒][-arkhncfF]时间 警告消息  
  3. -t:后面加描述表示过几秒之后关机。  
  4. -k:不是真的关机,仅仅发出警告消息。  
  5. -r:将系统服务停掉之后重启。  
  6. -h:将系统服务停掉之后立即关机。  
  7. -f:关机并开机之后,强制跳过fsck的磁盘检查。  
  8. -F:系统重启之后,强制进行fsck的磁盘检查。  
  9. -c:取消已经进行的shutdown命令内容。  
  10.   
  11. 另外,重启关机命令有reboot、halt、poweroff。其实在默认情况下,都完成一样的工作。  
  12. halt先调用shutdown,而shutdown最后调用halt。不过,shutdown可以根据目前已经启动的服务来逐次关闭服务后才关机;而halt能够在不理会目前系统情况下,进行硬件关机的特殊功能。  
  13.   
  14. 除了这些,还有一个关机命令是init 0  
  15. init是切换执行等级的命令。Linux共有7种执行等级,比较重要的是下面4种等级:  
  16. run level 0:关机  
  17. run level 3:纯命令行模式  
  18. run level 5:含有图形界面模式  
  19. run level 6:重启  

          十九、让自己的应用不被kill掉
可以在frameworks\base\services\java\com\android\server\am\ActivityManagerService.java这个类的forceStopPackage中加一个条件:
[java]  view plain copy
  1. public void forceStopPackage(final String packageName) {  
  2.         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)  
  3.                 != PackageManager.PERMISSION_GRANTED) {  
  4.             String msg = "Permission Denial: forceStopPackage() from pid="  
  5.                     + Binder.getCallingPid()  
  6.                     + ", uid=" + Binder.getCallingUid()  
  7.                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;  
  8.             Slog.w(TAG, msg);  
  9.             throw new SecurityException(msg);  
  10.         }          
  11.         long callingId = Binder.clearCallingIdentity();  
  12.         try {  
  13.             IPackageManager pm = ActivityThread.getPackageManager();  
  14.             int pkgUid = -1;  
  15.             synchronized(this) {  
  16.                 try {  
  17.                     pkgUid = pm.getPackageUid(packageName);  
  18.                 } catch (RemoteException e) {  
  19.                 }  
  20.                 if (pkgUid == -1) {  
  21.                     Slog.w(TAG, "Invalid packageName: " + packageName);  
  22.                     return;  
  23.                 }  
  24.                 //begin:加入一个判断条件  
  25.                 if (packageName.equals("你的进程名")) {  
  26.                     return;  
  27.                 }  
  28.                 //end: 加入一个判断条件                                forceStopPackageLocked(packageName, pkgUid);  
  29.             }  
  30.         } finally {  
  31.             Binder.restoreCallingIdentity(callingId);  
  32.         }  
  33.     }  

这样的话在任务管理器里可以保证KISS不掉的;
还有在这个方法上还有个方法clearApplicationUserData中保证如果是该进程就不让调用forceStopPackage()方法。
另:其他方法:
1,首先在你的service的onDestory方法里面写上启动你自己的代码,为什么要写这个?因为如果用户是在设置->应用程序->正在运行服务这里面杀掉你service的话会调用到onDestory方法的,这里就可以启动了,
2:监听屏幕关闭广播,屏幕已关闭,就启动服务。
3:监听屏幕解锁广播,一样的道理,这样,基本上,你的service就达到永不停止了。对用户来说有点变态,但很多软件都这样。
     二十、EditText获取焦点
[java]  view plain copy
  1. EditText.requestFoucus()  
由于收集内容较多,所以决定每20条分为一篇文章。如有不便,敬请谅解!  

记得2011年的时候,整理了android有用代码片段这篇文章,后来,越添加越多,很是不方便,决定,每20条为一篇,分开记载,很多内容是从别的博客上面转载而来,由于疏忽没有说明来处,敬请作者谅解!

         

 二十一、获取手机屏幕分辨率
[java]  view plain copy
  1. DisplayMetrics  dm = new DisplayMereics();  
  2.   
  3.         getWindowManager().getDefaultDisplay().getMetrics(dm);  
  4.   
  5.         float width = dm.widthPixels * dm.density;  
  6.   
  7.         float height = dm.heightPixels * dm.density  
     在这里问什么要乘以  dm.density   了,是因为通过dm.widthPixels的到的结果始终是320,不是真实的屏幕分辨率,所以要乘以dm.density得到真实的分辨率。
     二十二、在Activity里面播放背景音乐
[java]  view plain copy
  1. public void onCreate(Bundle savedInstanceState) {  
  2.              super.onCreate(savedInstanceState);  
  3.              setContentView(R.layout.mainlay);  
  4.              mediaPlayer = MediaPlayer.create(this, R.raw.mu);  
  5.              mediaPlayer.setLooping(true);  
  6.              mediaPlayer.start();  
  7.   
  8.                    }  


      二十三、让程序的界面不随机器的重力感应而翻转

                 第一种方法,在manifast文件里面

[html]  view plain copy
  1. <activity  
  2.   android:screenOrientation="portrait">  
  3.   </activity>  

                  第二种,在代码里面

[java]  view plain copy
  1. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  

     二十四、使activity全屏显示

[java]  view plain copy
  1. requestWindowFeature(Window.FEATURE_NO_TITLE);  
  2.         getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,        
  3.                 WindowManager.LayoutParams. FLAG_FULLSCREEN);  

        二十五、在RelativeLayout中使selector要注意点

         关于selector的使用方法,可以参考http://blog.csdn.net/aomandeshangxiao/article/details/6759576这篇文章,今天,遇到在RelativeLayout中添加background为selector后没有反应的问题,寻摸了很长时间,一直没有找到原因,其实只要加上一句代码就完全可以解决:

[java]  view plain copy
  1. <span style="font-size:16px;">RelativeLayout 里面加上android:clickable="true"</span>  

这样,RelativLayout就会出现在selector里面定义的效果。


   二十六、显示或隐藏虚拟键盘

[java]  view plain copy
  1. 显示:  
  2. InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));  
  3. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);  
  4.   
  5. 隐藏:  
  6. InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));  
  7. imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);  

   二十七、退出程序时清除通知中信息  

[java]  view plain copy
  1. NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);  
  2. nm.cancelAll();  

     二十八、创建快捷方式

[java]  view plain copy
  1. Intent intent=new Intent();  
  2. //设置快捷方式的图标  
  3. intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));  
  4. //设置快捷方法的名称  
  5. intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "点击启动哥的程序");            //设置点击快键图标的响应操作  
[java]  view plain copy
  1. intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));  
  2. //传递Intent对象给系统  
  3. setResult(RESULT_OK, intent);  
  4. finish();  

 

   二十九、获取文件中的类名:

[java]  view plain copy
  1. String path = context.getPackageManager().getApplicationInfo(  
  2.                                         context.getPackageName(), 0).sourceDir;  
  3.                         DexFile dexfile = new DexFile(path);  
  4.                         Enumeration<String> entries = dexfile.entries();  
  5.                         while (entries.hasMoreElements()) {  
  6.                                 String name = (String) entries.nextElement();  
  7.                                 ......  
  8.                         }  



三十. TextView中的getTextSize返回值是以像素(px)为单位的,

而setTextSize()是以sp为单位的.

所以如果直接用返回的值来设置会出错,解决办法是:

用setTextSize()的另外一种形式,可以指定单位:

[java]  view plain copy
  1. TypedValue.COMPLEX_UNIT_PX : Pixels    
  2. TypedValue.COMPLEX_UNIT_SP : Scaled Pixels    
  3. TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels  

三十一. 在继承自View时,绘制bitmap时,需要将图片放到新建的drawable-xdpi

中,否则容易出现绘制大小发生改变


三十二. 在文字中加下划线: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); 


三十三. scrollView是继承自frameLayout,所以在使用LayoutParams时需要用frameLayout

 

三十四、android阴影字体设置

 

[html]  view plain copy
  1. <TextView  android:id="@+id/tvText1"   
  2.  android:layout_width="wrap_content"   
  3.  android:layout_height="wrap_content"   
  4.  android:text="text1"   
  5.  android:textSize="30sp"   
  6.  android:textStyle="bold"   
  7.  android:textColor="#FFFFFF"   
  8.  android:shadowColor="#ff0000ff"  
  9.  android:shadowDx="5"  
  10.  android:shadowDy="5"       
  11.  android:shadowRadius="10"/>  


 

android:shadowColor 阴影颜色

android:shadowDx 阴影的水平偏移量

android:shadowDy 阴影的垂直偏移量

android:shadowRadius 阴影的范围

 

为了统一风格和代码的复用,通常可以把这个样式抽取放入到style.xml文件中

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <style name="textstyle">         
  4.         <item name="android:shadowColor">#ff0000ff</item>  
  5.         <item name="android:shadowRadius">10</item>  
  6.         <item name="android:shadowDx">5</item>  
  7.         <item name="android:shadowDy">5</item>       
  8.     </style>  
  9. </resources>  
[html]  view plain copy
  1. <TextView  
  2.         style="@style/textstyle"  
  3.         android:layout_width="fill_parent"  
  4.         android:layout_height="wrap_content"  
  5.         android:text="字体样式"  
  6.         android:textSize="30sp"  
  7.         android:textStyle="bold" />  

 

 三十五、android实现手机震动功能

[java]  view plain copy
  1. import android.app.Activity;  
  2. import android.app.Service;  
  3. import android.os.Vibrator;  
  4.   
  5. public class TipHelper {   
  6.     public static void Vibrate(final Activity activity, long milliseconds) {  
  7.         Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);  
  8.         vib.vibrate(milliseconds);  
  9.     }  
  10.     public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {  
  11.         Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);  
  12.         vib.vibrate(pattern, isRepeat ? 1 : -1);  
  13.     }  
  14. }  


还需要在AndroidManifest.xml 中添加震动权限:

[html]  view plain copy
  1. <uses-permission android:name="android.permission.VIBRATE" />  
通过上面操作,我们可以使用TipHelper所定义的函数了。两个Vibrate函数的参数简单介绍如下:

final Activity activity  :调用该方法的Activity实例

long milliseconds :震动的时长,单位是毫秒

long[] pattern     :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒

boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次

三十六、常用的正则表达式

       ^[\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号

三十七、输入框不挤压activity布局:

在manifest文件activity下 加:

[html]  view plain copy
  1. android:windowSoftInputMode="adjustPan"  

三十八、listview中item中button可点击:

[html]  view plain copy
  1. android:descendantFocusability="blocksDescendants"  

三十九、获取移动设备的IP地址:

[java]  view plain copy
  1. public class Tools {  
  2.     public static String getLocalIpAddress() {    
  3.         try {    
  4.             for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {    
  5.                 NetworkInterface intf = en.nextElement();    
  6.                 for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {    
  7.                     InetAddress inetAddress = enumIpAddr.nextElement();    
  8.                     if (!inetAddress.isLoopbackAddress()) {    
  9.                         return inetAddress.getHostAddress().toString();    
  10.                     }    
  11.                 }    
  12.             }    
  13.         } catch (SocketException ex) {    
  14.             Log.e("出错啦", ex.toString());    
  15.         }    
  16.         return null;    
  17.     }    
  18. }  
  19. 然后  
  20.         WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);  
  21.         WifiInfo wi = wm.getConnectionInfo();  
  22.         System.out.println("IP地址是:"+Tools.getLocalIpAddress());  
  23.         System.out.println("SSID:"+wi.getSSID());  
  24. 最后记得加两个权限  
  25.     <uses-permission android:name="android.permission.INTERNET"/>  
  26.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  


四十、高仿小米launcher跨屏拖动item(GridView长按item进行拖动

        触发长按事件后浮动原理:

     

[java]  view plain copy
  1. windowParams = new WindowManager.LayoutParams();  
  2.   windowParams.gravity = Gravity.TOP | Gravity.LEFT;  
  3.   windowParams.x = x - itemWidth / 2;  
  4.   windowParams.y = y - itemHeight / 2;  
  5.   windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;  
  6.   windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;  
  7.   ImageView iv = new ImageView(getContext());  
  8.   iv.setImageBitmap(bm);  
  9.   windowManager = (WindowManager) getContext().getSystemService(  
  10.   Context.WINDOW_SERVICE);// "window"  
  11.   windowManager.addView(iv, windowParams);  
       拖动效果:

[java]  view plain copy
  1. if (dragImageView != null) {  
  2.   windowParams.alpha = 0.6f;  
  3.   windowParams.x = x - itemWidth / 2;  
  4.   windowParams.y = y - itemHeight / 2;  
  5.   windowManager.updateViewLayout(dragImageView, windowParams);  
  6.   }  


前两个已经到第四十个了,所以还得再开一篇,用于记录,以前文章:Android有用代码片段(二)android有用代码片段,有需要的朋友可以去看一下。

         四十一、数据库写入图片信息:

[java]  view plain copy
  1. <span style="font-family:Tahoma, 'Microsoft Yahei', Simsun;color:#444444;">数据库中的字段设置为 binary类型  
  2. Bitmap bitmap = BitmapFactory.decodeFile(path);  
  3. ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  4.                 bitmap.compress(CompressFormat.JPEG, 50, baos);  
  5. String sql = "insert into pic_info(pic_data, pic_name,pic_size,send_date,is_success) " +"values(?,?,?,?,?)";  
  6.                 Object[] args = new Object[]{baos.toByteArray(), name, size, now, isSucess};  
  7. db.insert(sql, args);  
  8. 读取数据库的图片信息:  
  9. byte[] picData = cursor.getBlob(cursor.getColumnIndex("pic_data"));  
  10. bitmap.setImageBitmap(BitmapFactory.decodeByteArray(picData, 0, picData.length));</span>  

             四十二、listView的addView的问题。

         在listView里使用addView()、addFooterView(v)、addHeaderView(v)时,要在setAdepter以前添加,或者在重写的Adapter中添加。因为setAdapter以后,就是listView已经绘制完毕,不能再进行添加。

         四十三、progressBar修改颜色

        有的时候,我们使用progressBar的时候,后面的背景色是白色或者是亮色,使得progressBar效果很不明显,所以,我们可以在下面三条中随意添加一条熟悉就可以了:

[java]  view plain copy
  1. <ProgressBar style="@android:style/Widget.ProgressBar.Inverse"/>  
  2. <ProgressBar style="@android:style/Widget.ProgressBar.Large.Inverse"/>  
  3. <ProgressBar style="@android:style/Widget.ProgressBar.Small.Inverse"/>  

         这是比较简单的,如果要完成复杂效果,需要自定义style了。

       

        四十四、窗口透明(背景模糊等)

       先看下效果图:



第一种效果:

在styles.xml中定义

[html]  view plain copy
  1. <style name="Theme.Translucent" parent="android:style/Theme.Translucent">  
  2. <item name="android:windowBackground">  
  3. @drawable/translucent_background  
  4. </item>  
  5. <item name="android:windowNoTitle">true</item>  
  6. <item name="android:colorForeground">#fff</item>  
  7. </style>  

第二种效果是在源代码里面修改,在onCreate方法里面添加:

[java]  view plain copy
  1. getWindow().  
  2. setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,  
  3. WindowManager.LayoutParams.FLAG_BLUR_BEHIND);  
  4. setContentView(R.layout.translucent_background);  

设置模糊效果是通过窗口管理器(WindowManager)设置参数来完成的,这种设置只有在背景设置为透明后才能显示效果。


  四十五、Android输入框和文本框滚动条ScrollView

    我们都知道EditText与TextView是Android的文本输入框和文本显示框,但是基于手机屏幕的大小因素,如果在需要输入较多文字或者显示较多内容的时候,手机屏幕是远远不够的,因此让文本框具有滚动条的功能是手机上必备的,


要加上滚动条,其实很简单,只需要在文本输入框或者文本显示框上面加上滚动条控件即可,该控件名字为ScrollView,以下我们对比下(以TextView举例)。

A、未加滚动效果

[html]  view plain copy
  1. <TextView   
  2. android:layout_width="fill_parent"   
  3. android:layout_height="wrap_content"   
  4. android:id="@+id/textView"   
  5. />  

B、加上滚动效果

[html]  view plain copy
  1. <ScrollView   
  2. android:id="@+id/scrollView"   
  3. android:layout_width="fill_parent"   
  4. android:layout_height="200px"   
  5. android:scrollbarStyle="outsideOverlay" android:background="@android:drawable/edit_text">   
  6. <TextView   
  7. android:layout_width="fill_parent"   
  8. android:layout_height="wrap_content"   
  9. android:id="@+id/textView"   
  10. />   
  11. </ScrollView>  


由以上例子可以看出,只需要在文本控件的外围加上ScrollView控件就可以让文本框具有滚动体的功能。

       四十六、Android模拟器启动内存错误(内存不能为read)

如图

运行模拟器的时候总是会内存错误。




这种情况偶尔出现,没什么关系,不用管他。点击‘取消’就可以了。 
经常出现就危险了,弄不好就得重装系统了。 

运行某些程序的时候,有时会出现内存错误的提示,然后该程序就关闭。 
“0x????????”指令引用的“0x????????”内存。该内存不能为“read”。 
“0x????????”指令引用的“0x????????”内存,该内存不能为“written”。 
一般出现这个现象有方面的,一是硬件,即内存方面有问题,二是软件 

开始 运行 输入:cmd 确定: 

在DOS提示符下输入: 

for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1 

等待3分钟,左右后,搞定了。(如果怕输错,就把这句话复制上去)。

     

    

四十七、通过路径获取媒体文件信息

    通过路径获取媒体文件信息  http://blog.csdn.net/aomandeshangxiao/article/details/6600725

        四十八、Java中有用的文件操作

      java文件操作 http://blog.csdn.net/aomandeshangxiao/article/details/6597302

       

       四十九、Android文件读写

    Android文件的读写 http://blog.csdn.net/aomandeshangxiao/article/details/6589510

        五十、

     scaleType属性与ImagView中图片的显示的关系

      

    五十一、  Notification的属性

                           notification的各种属性:http://blog.csdn.net/aomandeshangxiao/article/details/6608101

   五十二、Android控件实现震动:

               先在res下面新创建anim文件夹,在该文件夹中创建shake.xml文件:

[java]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <translate xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:duration="1000"   
  4.     android:fromYDelta="0"   
  5.     android:toYDelta="10"  
  6.     android:fromXDelta="0"  
  7.     android:toXDelta="10"  
  8.     android:interpolator="@anim/cycle_7" />  

最后引用了cycle_7,再在该文件夹中创建cycle_7.xml文件

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   
  3. <cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:cycles="10" />  
  在Java代码里面:

[html]  view plain copy
  1. Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);  
  2.         findViewById(R.id.image).startAnimation(shake);  

就实现了该控件的震动效果。

         

    五十三、Android 页面切换动画效果

      http://hi.baidu.com/fountainblog/blog/item/66cb9918b0220eaa4bedbc2e.html

    五十四、Android2.2完全退出程序 

     http://www.eoeandroid.com/thread-62284-1-1.html

    五十五、Android按下back键非退出隐藏到后台

[java]  view plain copy
  1. public boolean onKeyDown(int keyCode, KeyEvent event) {    
  2.     if (keyCode == KeyEvent.KEYCODE_BACK) {    
  3.         Intent intent = new Intent(Intent.ACTION_MAIN);    
  4.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
  5.         intent.addCategory(Intent.CATEGORY_HOME);    
  6.         startActivity(intent);    
  7.         return true;    
  8.     }    
  9.     return super.onKeyDown(keyCode, event);    
  10. }    


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值