android 点滴

android点滴1
如何取得手机号码,手机串号,sim卡序列号?
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = tm.getDeviceId(); 
String tel = tm.getLine1Number(); //本机号码
String imei =tm.getSimSerialNumber();
String imsi =tm.getSubscriberId();
res.setText(deviceid+"#"+tel+"#"+imei+"#"+imsi);

注:并不是所有手机都能取到本机号码,中国电信手机(133)取不到号码。

如何让Activity失去任何按键和点击反应?
当我们链接网络时需要显示一个ProgressBar让用户等待。
但是这个时候点击屏幕上任何东西都是无效的,这个怎么设置?不能用ProgressDialog!
@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if (progress.isShown()) {
			return true;
		} else {
			return super.dispatchKeyEvent(event);
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		if (progress.isShown()) {
			return true;
		} else {
			return super.dispatchTouchEvent(ev);
		}
	}
	@Override
	public boolean dispatchTrackballEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		if (progress.isShown()) {
			return true;
		} else {
			return super.dispatchTrackballEvent(ev);
		}
	}


如何将中文设置成粗体?
在xml文件中使用android:textStyle="bold" 可以将英文设置成粗体,但是不能将中文设置成粗体,将中文设置成粗体的方法是: 
TextView tv = (TextView)findViewById(R.id.TextView01);
TextPaint tp = tv.getPaint();
tp.setFakeBoldText(true);

如何实现半透明的弹出框?
只需要把Manifest文件中注册的activity中添加android:theme="@android:style/Theme.Dialog"就可以了。如:
<activity android:name=".SettingActivity" android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@android:style/Theme.Dialog"></activity>

如何实现在自己的程序中点击一个按钮,然后弹出系统自带的联系人?
button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_VIEW);
				intent.setData(ContactsContract.Contacts.CONTENT_URI);//android2.X
				startActivity(intent);
			}
		});


如何打电话,发短信...等等?
1,调web浏览器
Uri myBlogUri = Uri.parse("http://xxxxx.com");
returnIt = new Intent(Intent.ACTION_VIEW, myBlogUri);
2,地图
Uri mapUri = Uri.parse("geo:38.899533,-77.036476");
returnIt = new Intent(Intent.ACTION_VIEW, mapUri);
3,调拨打电话界面
Uri telUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_DIAL, telUri);
4,直接拨打电话
Uri callUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_CALL, callUri);
5,卸载
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);
6,安装
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
7,播放
Uri playUri = Uri.parse("file:///sdcard/download/everything.mp3");
returnIt = new Intent(Intent.ACTION_VIEW, playUri);
8,掉用发邮件
Uri emailUri = Uri.parse("mailto:xxxx@gmail.com");
returnIt = new Intent(Intent.ACTION_SENDTO, emailUri);
9,发邮件
returnIt = new Intent(Intent.ACTION_SEND);
String[] tos = { "xxxx@gmail.com" };
String[] ccs = { "xxxx@gmail.com" };
returnIt.putExtra(Intent.EXTRA_EMAIL, tos);
returnIt.putExtra(Intent.EXTRA_CC, ccs);
returnIt.putExtra(Intent.EXTRA_TEXT, "body");
returnIt.putExtra(Intent.EXTRA_SUBJECT, "subject");
returnIt.setType("message/rfc882");
Intent.createChooser(returnIt, "Choose Email Client");
10,发短信
Uri smsUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_VIEW, smsUri);
returnIt.putExtra("sms_body", "yyyy");
returnIt.setType("vnd.android-dir/mms-sms");
11,直接发邮件
Uri smsToUri = Uri.parse("smsto://100861");
returnIt = new Intent(Intent.ACTION_SENDTO, smsToUri);
returnIt.putExtra("sms_body", "yyyy");
12,发彩信
Uri mmsUri = Uri.parse("content://media/external/images/media/23");
returnIt = new Intent(Intent.ACTION_SEND);
returnIt.putExtra("sms_body", "yyyy");
returnIt.putExtra(Intent.EXTRA_STREAM, mmsUri);
returnIt.setType("image/png");
最后一步:
startActivity(returnIt)

如何把Button或者ImageButton的背景设为透明或者半透明?
android:background=”@android:color/transparent”
or
android:background="@null"
or
半透明<Button android:background="#e0000000"/>
透明<Button android:background="#00000000"/>

如何在TextView显示HTML?
TextView tv=(TextView)findViewById(R.id.tv);
Spanned text = Html.fromHtml("<a href='http://www.baidu.com'>baidu</a>"); 
tv.setText(text);
如果html中有图片,请参考这篇文章:
http://da-en.iteye.com/blog/712415


如何修改软键盘默认为数字输入?
EditText editText = (EditText) findViewById(R.id.et); 
editText.setInputType(InputType.TYPE_CLASS_NUMBER); 

如何阻止EditText自动弹出输入法?
//EditText有焦点阻止输入法弹出
editText.setOnTouchListener(new OnTouchListener() {
				
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		//记住EditText的InputType现在是password 
		int inType = editText.getInputType(); // backup the input type
		editText.setInputType(InputType.TYPE_NULL); // disable soft input    
		editText.onTouchEvent(event); // call native handler    
		editText.setInputType(inType); // restore input type   
		editText.setSelection(editText.getText().length());
		return true;
					
	}
});

还可以试试:
EditText et=(EditText)findViewById(R.id.edit);
et.setInputType(InputType.TYPE_NULL);


如何设置半透明效果?
protected void onDraw(Canvas canvas) { 
super.onDraw(canvas); 
Paint paint = new Paint(); 
paint.setColor(Color.BLUE); 
paint.setAlpha(0x40);
canvas.drawXXX(...); 
}
注意setColor和setAlpha的位置不要颠倒,否则无效!

如何让TextView中的文字居中显示?
android:gravity="center"

如何删除模拟器上安装的apk?


android中文资源
http://www.cnblogs.com/over140/default.html?page=1

如何自定义标题栏?
//首先需要请求对FEATURE_CUSTOM_TITLE操作
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
view = new SnakeView(this);
setContentView(view);
//然后设置
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

R.layout.title对应的布局文件:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"     >
	<TextView
	android:id="@+id/title"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:layout_weight="1"
	android:layout_gravity="center"
	android:gravity="center" 
	android:text="Snake"
	android:textColor="@color/red"
	/>
</LinearLayout>

效果如下:

这里需要注意,最好不要修改背景色,否则会出现标题栏不会被充满的问题(会露马脚啦:)),如果确实需要修改背景色又不漏马脚,那么请看这篇文章:
http://www.iteye.com/topic/760314

在View中绘制文本,如何获得文本高度和宽度?
FontMetrics对象的四个基本坐标基准分别为:
・FontMetrics.top
・FontMetrics.ascent
・FontMetrics.descent
・FontMetrics.bottom

获得高度:
FontMetrics fm = paint.getFontMetrics();// 得到系统默认字体属性  
float fontHeight = fm.descent - fm.top;// 获得字体高度 
也可以这样:
float fontHeight = fm.bottom - fm.top;// 获得字体高度,与上面稍微有些差别,见图。
还可以这样:
paint.getTextSize();// 获得字体高度,简单一点就这样啦,区别不是太大。

获得宽度:
paint.getTextWidths(text, widths[]),widths是每个字符的宽度,维度不小于字符数。
还可以这样:
paint.measureText(text)
canvas.drawText("坐标测试", 0, 0, paint);//在屏幕上能看见吗?(不全屏的话)
canvas.drawText("坐标测试", 0, paint.getTextSize(), paint);//这个可以看到
canvas.drawText("坐标测试", 0, fontMetrics.bottom-fontMetrics.top, paint);//这个也可以看到

startManagingCursor(cursor)的作用是什么?
startManagingCursor可以让cursor也纳入到Activity的生命周期里。比如当activity stopped,就自动调用cursor.deactivate();当activity restarted,就自动调用cursor.requery()。省事!
通常都是这样使用:
Cursor cursor=db.query(XXX);//db为SQLiteDatabase对象
startManagingCursor(cursor);

startActivity(intent)和startActivityForResult(intent, requestCode)有什么区别?
startActivity(Intent)用于界面的跳转;
startActivityForResult()用于界面的相互跳转,比如Activity1 跳转到 Activity2,但是还需要在Activity2 再回到 Activity1呢? 可能有人说: 那我在Activity2  再使用 startActivity() 不就可以了,是的。但是startActivityForResult能够直接完成这项工作。
其中int requestCode:用于标识该Intent 回来后确定是不是想要的返回。
setResut(int resultCode, Intent intent)
resultCode 如果子模块可能有几种不同的结果返回,可以用这个参数予以识别区分。如果成功可以使用 RESULT_OK 值。之后可以在回调函数
protected void onActivityResult(int requestCode, int resultCode, Intent data){
     super.onActivityResult(requestCode, resultCode, data);
     switch (resultCode) {
		case RESULT_OK:
                doSomething();
                break;
            }
}

中处理需要做的事情。

ListView中getSelectedItemId()和getSelectedItemPosition()有和区别?
getSelectedItemId()获得的是对应数据库(如果使用了sqlite)中记录的id;比如:屏幕上看到的第3项,并不一定是数据库中的第3项。getSelectedItemId()获得的就是数据库中的第几项!这个很重要!操作数据的时候不会错乱了。
getSelectedItemPosition()获得的是绝对位置,就是指屏幕中第几项,从0开始。

长按菜单ContextMenu中如何获得ListView中的item?
public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info=(AdapterContextMenuInfo)item.getMenuInfo();//MenuItem中的信息全在AdapterContextMenuInfo中被封装
		switch (item.getItemId()) {
		case Menu.FIRST:
			doSomething(info.id);//注意这里
			return true;
		case Menu.FIRST+1:
			doOthers(info.id);
			return true;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}


如何通过Button弹出Menu?
this.openOptionsMenu();

android中如何清屏?
canvas.drawColor(Color.BLACK); 

如何改变Dialog背景透明度?
Dialog dg = new Dialog(this);
Window window = dg.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.alpha = 0.5f;
window.setAttributes(lp);
//lp.alpha = 0.5f 透明度设置 其值要合理 自己反复测试
//为什么要这个技巧 因为很多人说:弹出Dialog会导致背景变暗 有Animation发生 导致性能变慢 可以用这个改变之 而且可以借助这个 使得全透明 不挡住Dialog后面内容的显示


如何隐藏状态栏?
隐藏 状态栏 即:最上方的信号强度 3G网络 等属性 
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        	    WindowManager.LayoutParams.FLAG_FULLSCREEN);

其它使用: 
this.getWindow().setFlags(WindowManager.LayoutParams.TYPE_STATUS_BAR, WindowManager.LayoutParams.TYPE_STATUS_BAR);


如何隐藏标题栏?
即:应用程序名称的那一栏
//注意:2行代码的先后顺序不能颠倒
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//同时使用隐藏状态栏可以使可视面积最大化!
或者也可以在Manifest文件中这样设置:
<application android:icon="@drawable/icon"
  android:label="@string/app_name"
  android:theme="@android:style/Theme.NoTitleBar">


如何设置横屏?
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


如何取得屏幕宽高?
DisplayMetrics dm=new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth=dm.widthPixels;
        int screenHeight=dm.heightPixels;

Android获取屏幕高度、标题高度、状态栏高度详解 
http://www.iteye.com/topic/828830

如何设置屏幕方向?
可以在AndroidManifest.xml 文件中,通过<activity> 标记的screenOrientation 属性进行设定,例如:
<activity
	android:name=".SketchpadActivity"
	android:screenOrientation="landscape"/><!--让该Activity总是显示为横屏-->

screenOrientations属性共有7中可选值(常量定义在 android.content.pm.ActivityInfo类中 ) :
landscape:横屏(风景照) ,显示时宽度大于高度;
portrait:竖屏 (肖像照) , 显示时 高 度大于 宽 度 ;
user:用户当前的首选方向;
behind:继承Activity堆栈中当前Activity下面的那个Activity的方向;
sensor:由物理感应器决定显示方向,它取决于用户如何持有设备,当 设备 被旋转时方向会随之变化——在横屏与竖屏之间;
nosensor:忽略物理感应器——即显示方向与物理感应器无关,不管用户如何旋转设备显示方向都不会随着改变("unspecified"设置除外);
unspecified :未指定,此为默认值,由Android系统自己选择适当的方向,选择策略视具体设备的配置情况而定,因此不同的设备会有不同的方向选择;
也可以在代码中设置屏幕方向,例如:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//设置横屏

如何判断横竖屏?
在activity中重写这个方法 
@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    // TODO Auto-generated method stub 
    super.onConfigurationChanged(newConfig); 
    if (this.getResources().getConfiguration().orientation == 
         Configuration.ORIENTATION_PORTRAIT) {//竖屏 
         //doSomrthing 
    } else { 
        //横屏时dosomething 
    } 

每一次横屏和竖屏都会调用这个方法

如何实现国际化?
比如需要程序在中文和英文环境中切换,
首先在工程res文件夹中依次新建values-en和values-zh-rCN等资源文件夹,将string.xml文件翻译成英文,放入相应的资源文件夹内。
然后在模拟器主菜单中依次选择setting->Locale&Text->Select Locale,选择需要的语言即可。当找不到相应的语言系时,默认使用values文件夹下的string.xml
values目录名称与改写后对应的支持语言关系如下:
values-zh-rCN,简体中文
values-zh-rTW,繁体中文
values-ja,日文
values-en,英文
values-en-rUS,美式英文
values-en-rUK,英式英文

如何在程序中通过button切换中英文环境?
基本代码如下(按了button后需要退回到主菜单,然后再进入程序语言环境就变了):
locale=(Button)findViewById(R.id.locale);
        locale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Resources res=getResources();
				Configuration config=res.getConfiguration();
				if(config.locale==Locale.SIMPLIFIED_CHINESE){
					config.locale=Locale.ENGLISH;
				}else{
					config.locale=Locale.SIMPLIFIED_CHINESE;
				}
				DisplayMetrics dm=res.getDisplayMetrics();
				res.updateConfiguration(config, dm);
			}
        	
        });


如何手动签名应用程序?
1,打包成未签名apk包
在工程上右击,选择Android Tools->Export Unsigned Application Package
2,生成密钥
打开cmd,并进入cd C:\Program Files\Java\jdk1.6.0_20\bin
keytool -genkey -v -keystore XXX.keystore -alias XXX.keystore -keyalg RSA -validity 20000
然后依次输入各项即可
3,开始签名
jarsigner -verbose -keystore XXX.keystore -signedjar 你的应用名称_signed.apk 你的应用名称.apk XXX.keystore
4,验证密钥(非必需,但建议)
jarsigner -verify -verbose -certs 你的应用名称_signed.apk

如何使用eclipse自动生成已验证的apk包?
如果觉得手动签名比较麻烦,那么使用自动签名吧。
在工程上右击,选择Android Tools->Export Application Package

然后依次填入各项,这里特别注意Keystore selection这一步,如果已生成keystore,则选第一项;如果还没有,则选第二项。


android点滴2
如何让Drawable绕着中心旋转?

Animation a = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
a.setRepeatCount(-1);
a.setDuration(1000);


如何控制Android LED灯颜色?
很多Android手机上都配有LED灯,比如HTC的手机在充电、新来短信等时候都会有响应的指示,其实很简单的这都是NotificationManager的一些参数而已,下面Android123给大家说下如何通过代码控制LED灯的闪烁,因为有些机型没有LED灯或颜色种类较少,发布时需要真机观察。
final int ID_LED=19871103; 
NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(); 
notification.ledARGB = 0xFFFFFF;  //这里是颜色,我们可以尝试改变,理论上0xFF0000是红色,0x00FF00是绿色
notification.ledOnMS = 100; 
notification.ledOffMS = 100; 
notification.flags = Notification.FLAG_SHOW_LIGHTS; 
nm.notify(ID_LED, notification); 
nm.cancel(ID_LED);


如何获取APK文件安装时间?
很多Android开发者想设计一个APK管理程序,获取APK文件的安装日期很多网友不是很明白。在早期Android123使用的方法是通过PackageManager类的getInstalledApplications方法返回一个ApplicationInfo数组,ApplicationInfo类中sourceDir可以获取APK的文件路径,从而使用File类读取文件的上次修改时间而实现。但这可能导致:
1. 无法获取原始的创建时间,可能很早就被创建了,之后被替换了。
2. 如果这个APK在一个私有的位置,比如app-private目录,使用Market付费购买的应用在这个位置,如果没有Root的Android手机是没有权限读取的,也导致获取时间失败。
在Android 2.3 API Level为9中,ApplicationInfo类新增的firstInstallTime和lastUpdateTime这两个字段,可以直接获取到APK的创建或上次修改的时间,即使是付费软件也能正常的获取。

如何区别单位px和dp以及sp?
px (pixels)像素 -- 一般我们HVGA代表320x480像素,这个用的比较多。
dip或dp (device independent pixels)设备独立像素 -- 这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA cwj推荐使用这个,不依赖像素。
sp (scaled pixels — best for text size)放大像素-- 主要处理字体的大小。
下面的几个是不常用的,大家也知道这里android123就不再过多的赘述。
in (inches)英寸
mm (millimeters)毫米  
pt (points)点


如何动态改变ImageView大小?
很多网友可能发现在layout.xml文件中定义了ImageView的绝对大小后,无法动态修改以后的大小显示,其实Android平台在设计UI控件时考虑到这个问题,为了适应不同的Drawable可以通过在xml的相关ImageView中加入android:scaleType="fitXY" 这行即可,但因为使用了缩放可能会造成当前UI有所变形。使用的前提是限制ImageView所在的层,可以使用一个内嵌的方法限制显示。

如何在Android中最简单的播放GIF动画?
GIF动画的原理就是逐帧播放,在Android中提供了AnimationDrawable类可以实现,有的网友写过GIF89A的解码方法在过去的J2ME平台移植到Android平台也能用,其实在Google Android上面开发目前2.2以后的固件支持的方法除了Flash Player外,更好的兼容方法就是使用万能的webkit浏览器了,我们直接在工程中内嵌一个webView,html中只要写上类似img src="http://android123.com.cn/cwj.gif" 这样的就可以了,当然了路径大家可以换成本地的,对于浏览器使用本地资源url为file://开头。 不过webView的资源消耗也不小,开个webView对象可能占用了至少8MB的RAM吧,保守估计,当然更多的要看插件和以及html的复杂程度所决定的。

如何调用手机系统拨号页面?
/*调出联系人界面*/
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(ContactsContract.Contacts.CONTENT_URI);//android2.X
startActivity(intent);

/* 调用拨号的画面 */
Intent myIntentDial = new Intent("android.intent.action.CALL_BUTTON");
startActivity(myIntentDial);

加权限:
<uses-permission android:name="android.permission.CALL_PHONE" />

如何取得GPS卫星个数?
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Iterator<GpsSatellite> iterator = manager.getGpsStatus(null).getSatellites().iterator();
int count = 0;
while (iterator.hasNext()) {
        count++;
}
return count; 


如何判断手机有无网络?
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null) {
			if (cwjManager.getActiveNetworkInfo().isAvailable()) {
				String type = cwjManager.getActiveNetworkInfo().getTypeName();
				System.out.println("_____________________-" + type);
			}
			;
		}else {
			System.out.println("_____________________-" + cwjManager.getActiveNetworkInfo());
		}

如果拟开发一个网络应用的程序,首先考虑是否接入网络,在Android手机中判断是否联网可以通过 ConnectivityManager 类的isAvailable()方法判断,首先获取网络通讯类的实例,使用cwjManager.getActiveNetworkInfo().isAvailable(); 来返回是否有效,如果为True则表示当前Android手机已经联网,可能是WiFi或GPRS、HSDPA等等,具体的可以通过ConnectivityManager 类的getActiveNetworkInfo() 方法判断详细的接入方式,需要注意的是有关调用需要加入<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 这个权限,在真机上Market和Browser程序都使用了这个方法,来判断是否继续,同时在一些网络超时的时候也可以检查下网络连接是否存在,以免浪费手机上的电力资源。

如何获得自己程序的版本?
 private String mVersion;   
public String longVersion() {  
        if (mVersion == null) {  
            PackageManager pm = getPackageManager();  
            PackageInfo pi;  
            try {  
                pi = pm.getPackageInfo(getPackageName(), 0);  
                mVersion = pi.versionName;  
                System.out.println("mVersion-----------------> "+mVersion);  
            } catch (NameNotFoundException e) {  
                mVersion = ""; // failed, ignored  
            }  
        }  
        return mVersion;  
}  


drawable- hdpi、drawable- mdpi、drawable-ldpi的区别:
在之前的版本中,只有一个drawable,而2.1版本中有drawable-mdpi、drawable-ldpi、drawable-hdpi三个,这三个主要是为了支持多分辨率。 
(1)drawable-hdpi里面存放高分辨率的图片,如WVGA (480x800),FWVGA (480x854) 
(2)drawable-mdpi里面存放中等分辨率的图片,如HVGA (320x480) 
(3)drawable-ldpi里面存放低分辨率的图片,如QVGA (240x320) 
    系统会根据机器的分辨率来分别到这几个文件夹里面去找对应的图片。在开发程序时为了兼容不同平台不同屏幕,建议各自文件夹根据需求均存放不同版本图片。

如何理解Context?
Context字面意思上下文。
    位于framework package的android.content.Context中,其实该类为LONG型,类似Win32中的Handle句柄,很多方法需要通过Context才能识别调用者的实例,比如说Toast的第一个参数就是Context,一般在Activity中我们直接用this代替,代表调用者的实例为Activity,而到了一个button的onClick(View view)等方法时,我们用this时就会报错,所以我们可能使用ActivityName.this来解决,主要原因是因为实现Context的类主要有Android特有的几个模型,Activity、Service以及BroadcastReceiver。 
    常规需要Context实例的方法主要有各种Service实现的类,比如说SensorManager在实例化时需要getSystemService(String)方法就必须由Context的实例执行,还有一些私有的文件系统I/O比如说openFileInput以及常用的Toast的makeText方法等。

如何为Android MapView申请apiKey?
1.首先先要获取你的debug keystore位置: 
  打开Eclipse--->Windows--->Preferences--->Android--->Build 
查看默认的debug keystore位置,我的是C:\Documents and Settings\Android123\.android\debug.keystore 
2.在cmd中执行: 
  keytool -list -alias androiddebugkey -keystore "C:\Documents and Settings\Android123\.android\debug.keystore" -storepass android -keypass android 
  双引号中的为你keystore位置 
  执行结果: 
  androiddebugkey, May 4, 2009, PrivateKeyEntry, 
  Certificate fingerprint (MD5): XX:XX:XX:XX:XX:XX:XX:XX............. 
  这里的XX:XX:XX:XX:XX:XX:XX:XX.............就是你的认证指纹 
3.打开http://code.google.com/intl/zh-CN/android/maps-api-signup.html 
填入你的认证指纹(MD5)即可获得apiKey了,结果显示如下: 
  您的密钥是:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 
4.使用得到的apiKey:在layout中加入MapView 
  <com.google.android.maps.MapView 
          android:id="@+id/mapview" 
          android:layout_width="fill_parent" 
          android:layout_height="fill_parent" 
          android:apiKey="XXXXXXXXXXXXXXXXXXXXXXXXXXXX" />

如何理解onInterceptTouchEvent()事件处理点击的承继关系?
onInterceptTouchEvent()的机制: 
1. down事件首先会传递到onInterceptTouchEvent()方法 
2. 如果该ViewGroup的onInterceptTouchEvent()在接收到down事件处理完成之后return false, 
   那么后续的move, up等事件将继续会先传递给该ViewGroup,之后才和down事件一样传递给最 
   终的目标view的onTouchEvent()处理 
3. 如果该ViewGroup的onInterceptTouchEvent()在接收到down事件处理完成之后return true, 
   那么后续的move, up等事件将不再传递给onInterceptTouchEvent(),而是和down事件一样 
   传递给该ViewGroup的onTouchEvent()处理,注意,目标view将接收不到任何事件。 
4. 如果最终需要处理事件的view的onTouchEvent()返回了false,那么该事件将被传递至其上一 
   层次的view的onTouchEvent()处理 
5. 如果最终需要处理事件的view 的onTouchEvent()返回了true,那么后续事件将可以继续传递 
   给该view的onTouchEvent()处理

如何彻底关闭android应用程序(back按键)?
在开发android应用时,常常通过按返回键(即keyCode == KeyEvent.KEYCODE_BACK)就能关闭程序,其实大多情况下该应用还在任务里运行着,其实这不是我们想要的结果。 
我们可以这样做,当用户点击自定义的退出按钮或返回键时(需要捕获动作),我们在onDestroy()里强制退出应用,或直接杀死进程,具体操作代码如下: 
@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		//按下键盘上返回按钮
		if(keyCode == KeyEvent.KEYCODE_BACK){
						finish();
			return true;
		}else{		
			return super.onKeyDown(keyCode, event);
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		System.exit(0);
		//或者下面这种方式
		//android.os.Process.killProcess(android.os.Process.myPid()); 
	}


如何让所有Activty界面全去掉标题栏?
修改AndroidManifest.xml ,在application 标签中添加 。
android:theme="@android:style/Theme.NoTitleBar"

当同时有多个ImageView共同使用同一个资源文件例如:demo.png的时候,如果我们在利用代码控制其中一个ImageView的状态例如:alpha的时候,同时也会影响到别的ImageView的状态,这个时候我们可以通过下面的办法来避免这种情况的发生: 
//res_ico 是一个图片资源文件id R.drawable.***
Drawable ico = getResources().getDrawable(res_ico);
ImageView iv = new ImageView(this);
iv.setBackgroundDrawable(ico);
iv.setClickable(false);
iv.setAdjustViewBounds(true);
ico.mutate().setAlpha(20);


如何判断GPS是否打开以及跳转到设置GPS界面?
检查GPS是否打开
locationManager.isProviderEnabled("gps"); 

转到GPS设置界面
startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));


如何获取手机版本等信息?
// 获取手机SDK 版本和版本号
System.out.println("version-> "+android.os.Build.VERSION.SDK);
System.out.println("version-> "+android.os.Build.VERSION.RELEASE);	
//获取产品型号
System.out.println("version-> "+android.os.Build.MODEL);


如何在Android开发之模拟按下Home键的效果 ?
 Intent i= new Intent(Intent.ACTION_MAIN);
 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
//如果是服务里调用,必须加入new task标识
 i.addCategory(Intent.CATEGORY_HOME);


如何杀死进程?
在Android 2.2中新增了一个API可以帮助我们杀死后台进程,不过其调用的API Level最小为8,killBackgroundProcesses是android.app.ActivityManager类的方法,使用时必须在androidmanifest.xml文件中加入KILL_BACKGROUND_PROCESSES这个权限。
该方法的原型 public void killBackgroundProcesses (String packageName)  仅有一个参数为package Name,使用方法比较简单:
 ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
am.killBackgroundProcesses("cn.com.android123.cwj");   
// API Level至少为8才能使用


如何在子线程中通过handler操作界面元素?
android.os.Handler hander = new android.os.Handler();					hander.postDelayed(new Runnable()
{
public void run()
{
  ad.dismiss();
}
}, 5 * 1000);

如何清除桌面墙纸?
clearWallpaper();


不过我们需要设置墙纸更改权限:
<uses-permission android:name="android.permission.SET_WALLPAPER" />


如何申请访问SDCard的权限?
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
android点滴3
到android设置中的卸载界面
Uri uri = Uri.fromParts("package", appInfo.packageName, null);     
Intent it=new Intent();
it.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
it.setData(uri);
startActivity(it);


清除手机Cookie:
    CookieManager.getInstance().removeAllCookie();

向Handler发送Message方法:
mHandler.obtainMessage().sendToTarget();//没试过
mHandler.sendMessage(new Message()); 

自定义权限:
    在应用One中定义并声明权限:
    定义:
    <permission
           android:name = "com.focus.fishme.permission.READ"
           android:label = "@string/permission_read"
           android:description = "@string/permission_read_detail"
           />
    声明:
     <activity
            android:name = ".ReadActivity"
            android:permission = "com.focus.fishme.permission.READ"
            />
    在应用Two中调用应用One中的ReadActivity。
    使用:
    <uses-permission android:name = "com.focus.fishme.permission.READ"/>

android:sharedUserId说明
    在Android中每个应用程序都会分配一个单独的用户空间,可以通过设置AndroidManifest.xml文件manifest标签的
    android:sharedUserId属性指定相同的值,使多个APK运行在同一个用户空间中,在不同APK中共享数据库或配置信息。

获取屏幕上正在显示的Activity:
    (1)ActivityManager mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    (2)ComponentName mComponentName = mActivityManager.getRunningTasks(1).get(0).topActivity; 

判断Activity是否在系统中存在:
    Intent intent = new Intent();
    intent.setClassName("包名", "类名");
    if(intent.resolveActivity(getPackageManager()) == null) {

    }

Android中获取位图的三种方法:
(1)InputStream mInputStream = getResources().openRawResource(R.drawable.图片名);
BitmapDrawable mBitmapDrawable = new BitmapDrawable(mInputStream);
Bitmap mBitmap = mBitmapDrawable.getBitmap();
(2)BitmapDrawable mBitmapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.图片名);
Bitmap mBitmap = mBitmapDrawable.getBitmap();
(3)Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.图片名);

如何刷新View?
在UI线程中调用invalidate()方法,在非UI线程中调用postInvalidate()方法。

如何在一个apk中调用另外一个apk中的activity?
   系统提供了很多可以直接调用的Activity,通过指定的Intent就可以调用,比如打开搜索的:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);

     Intent.ACTION_WEB_SEARCH是一个字符串,是“搜索”这个Activity的标识,extra是传给这个activity的一些数据。发送出这个intent之后,系统根据action字符串Intent.ACTION_WEB_SEARCH知道了是要调用哪个activity,如果有重名,会弹出一个选择对话框。然后打开此activity,实现想要做的事情。
    那么,我们自己怎么来实现呢。
    首先,写一个activity,在AndroidManifest.xml里面的intent-filter中,给这个activity命名,
<intent-filter>
        <action android:name="chroya.foo"/>
        <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

    然后安装。安装完毕之后,你会发现,系统中找不到这个程序。别急,它确实安装在手机里面了,但是因为他不是main的,所以系统不会把他当做Application的入口程序。
    而要想打开这个activity,只有知道它名字的人才可以。跟系统的intent一样使用。它的名字定义为"chroya.foo",所以,这里用这个字符串就可以调用它了:
Intent intent = new Intent("chroya.foo");
startActivity(intent);

       用刚才举的那个系统的intent说明,它的activity里面使用getIntent().getBundleExtra(SearchManager.QUERY)来接收传递进来的搜索字符串参数。而这个SearchManager.QUERY是关键字。如果要自己实现这种功能,只需要定义好关键字,然后从BundleExtra中取就行了。

如何获取屏幕上正显示的activity?
       用过ActivityManager的童鞋估计都知道,可以从ActivityManager里面可以获取到当前运行的所有任务,所有进程和所有服务,这是任务管理器的核心。
         那么,从里面我们可以发掘点什么出来吗?
         仔细看getRunningTasks的文档,里面说获取的是系统中"running"的所有task,"running"状态包括已经被系统冻结的task。而且返回的这个列表是按照顺序排列的,也就是说第一个肯定比第二个后运行。
          getRunningTasks有个整型参数,表示返回列表的最大个数。那么,我们如果把1作为参数给进去,那么他返回的task就是当前运行的那个task,然后从task中获取到最顶层的activity,这个activity就是当前显示给用户的那个activity了。
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.d("", "pkg:"+cn.getPackageName());
Log.d("", "cls:"+cn.getClassName()); 

       至于这个能做什么,嘿嘿,我相信你知道的。

如何判断一个activity是否存在于系统中?
已知包名和类名,如何判断这个activity是否在系统中存在呢?很简单,通过intent就行。
        Intent intent = new Intent();
        intent.setClassName("包名", "类名");      
        if(getPackageManager().resolveActivity(intent, 0) == null) {
        	//说明系统中不存在这个activity
        }


如何让应用程序动态全屏和退出全屏?
    让程序全屏的方法,大家都知道,那是静态的,程序运行之初就申明了。但是如果有这样的需求:要在程序运行的过程中,执行了某个操作而使之全屏,然后还需要退出全屏,怎么做?
    如下:
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

    修改window的LayoutParams参数,然后加上FLAG_LAYOUT_NO_LIMITS标志,就OK了。window会自动重新布局,呈现全屏的状态。
    要退出全屏,只需要清除刚才加上的FLAG_FULLSCREEN参数,然后去掉FLAG_LAYOUT_NO_LIMITS标志。
    如下:
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setAttributes(attrs);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);


如何获取状态栏和标题栏的高度?
1.获取状态栏高度:
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。于是,我们就可以算出状态栏的高度了。
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top; 

2.获取标题栏高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight;


如何将一个视窗(windows)盖在整个Application的最上面?
 private ImageView waitView;
private final void showWaiting() {
 try {
WindowManager.LayoutParams lp = null;
lp = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_TOAST ,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
| WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;
WindowManager mWindowManager = (WindowManager) G.appInstance
.getSystemService(Context.WINDOW_SERVICE);
if (waitView == null) {
LayoutInflater inflate = (LayoutInflater) G.appInstance
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,
null);
}
mWindowManager.addView(waitView, lp);
} catch (Throwable e) {
}
}

注意: 
1. 要将window的类型配置成Type_toast。 
2.G.appInstance 上下文需要使用Application的context. 

如何判断快捷方式是否已经创建?
快捷方式信息是保存在com.android.launcher的launcher.db的favorites表中
		boolean isInstallShortcut = false ;
		final ContentResolver cr = context.getContentResolver();
		final String AUTHORITY = "com.android.launcher.settings";
		final Uri CONTENT_URI = Uri.parse("content://" +
			             AUTHORITY + "/favorites?notify=true");
		
		Cursor c = cr.query(CONTENT_URI,
		new String[] {"title","iconResource" },
		"title=?",
		new String[] {"XXX" }, null);//XXX表示应用名称。
				if(c!=null && c.getCount()>0){
			isInstallShortcut = true ;
		}
		/*try {
			while (c.moveToNext()) {
                                     String tmp = "";
				tmp = c.getString(0);
			}
			} catch (Exception e) {

			} finally {
				c.close();
			}*/
		return isInstallShortcut ;
	}

要有权限: 
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
注意:2.2及其之后的版本不能用这个方法判断!(虽然在launcher.db数据库里还有favorites这个表)

如何在android的一个应用中调用另外一个应用?
Intent intent = new Intent();
//第一个参数另一个应用的包名,第二个是需要启动的类
intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));
startActivity(intent);


如何获取程序版本号?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.yourcompany.yourapp" 
   android:versionCode="109"
   android:versionName="0.1.6.109 dev">
   ...
</manifest>
 public static int getVersionCode(Context context) {
   PackageManager pm = context.getPackageManager();
   try {
      PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
      return pi.versionCode;
   } catch (NameNotFoundException ex) {}
   return 0;
}


如何让Toast充满全屏?
Toast t = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT);
t.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);


如何更高效简单的实现界面中的分隔线?
<View  
    android:layout_width="fill_parent"   
    android:layout_height="1px"   
    android:background="?android:attr/listDivider"   
/>


如何发起或删除另一个程序?
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( intent);

//ComponentName 两个参数一个是包名 一个是包下的主类
Uri uri = Uri.fromParts("package",“Your Package name here”, null);
Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);
startActivity(deleteIntent);


如何监测是否静音?
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE); 
switch (am.getRingerMode()) { 
    case AudioManager.RINGER_MODE_SILENT: 
        Log.i("MyApp","Silent mode"); 
        break; 
    case AudioManager.RINGER_MODE_VIBRATE: 
        Log.i("MyApp","Vibrate mode"); 
        break; 
    case AudioManager.RINGER_MODE_NORMAL: 
        Log.i("MyApp","Normal mode"); 
        break; 
} 


如何设置控件的随机显示位置?
RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();
parms.leftMargin = (int) (Math.random() * 320);
parms.topMargin = (int) (Math.random() * 480);
img.setLayoutParams(parms);        
img.invalidate();


如何让软键盘显示/消失?
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);    
View view = getCurrentFocus();    
if (view != null){    
     // imm.showSoftInput(view, 0); //显示软键盘    
      imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
     // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隐藏软键盘  // InputMethodManager.HIDE_NOT_ALWAYS);  
}  


如何为Activity屏幕的标题栏添加图标?
@Override  
public void onCreate(Bundle icicle) {  
    super.onCreate(icicle);  
    Window win = getWindow();  
    win.requestFeature(Window.FEATURE_LEFT_ICON);      
    setContentView(R.layout.mylayout);   
    win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);  
}

要注意的是,win.setFeatureDrawableResource必须在setContentView之后,不然就没有效果。

如何设置桌面壁纸?
希望在你的程序中能设置桌面壁纸吗?很简单,首先我们需要取得设置壁纸的权限。和其它权限一样,只要在配置文件中加上以下配置信息即可。
<uses-permission android:name="android.permission.SET_WALLPAPER" />
然后在程序中调用如下代码即可设置桌面壁纸:
getApplicationContext().setWallpaper(bitmap)

如何在标题栏(titlebar)显示进度条?
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先给Activity注册界面进度条功能
		setContentView(R.layout.main);
		setProgressBarIndeterminateVisibility(true);//在需要显示进度条的时候调用这个方法
		setProgressBarIndeterminateVisibility(false);//在不需要显示进度条的时候调用这个方法
}


如何去掉activity顶部的gradient?
<style name="Theme.Foo" parent="android:style/Theme.Light"> 
    <item name="android:windowContentOverlay">@null</item> 
</style>
<activity android:name=".FooActivity" 
          android:theme="@style/Theme.Foo"> ... 
http://wang-peng1.iteye.com/blog/680015

如何让ScrollView强制滑到底部?
scroll.fullScroll(View.FOCUS_DOWN) 就可以了

如何ViewFlipper去掉多余空间?
ViewFlipper flipper = (ViewFlipper)findViewById(R.id.flipper); 
flipper.setMeasureAllChildren(false); 

如何去掉tabhost横线?
很简单 简单的有时候是因为我们太浮躁
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
 
    android:gravity="center_horizontal">       
   <TabHost  
    android:id="@android:id/tabhost"     
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
... 
... 
... 
    </TabHost> 
    </LinearLayout> 
外面加一层LinearLayout


如何判断国家?
String locale = context.getResources().getConfiguration().locale.getCountry();  
String locale = context.getResources().getConfiguration().locale.getDisplayCountry(); 
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
String countryCode = tm.getSimCountryIso(); 


如何让屏幕保持一直亮?
@Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

http://wang-peng1.iteye.com/blog/769561

如何检查sim卡状态?
TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    int simState = telMgr.getSimState();
            switch (simState) {
                case TelephonyManager.SIM_STATE_ABSENT:
                    // do something
                    break;
                case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                    // do something
                    break;
                case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                    // do something
                    break;
                case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                    // do something
                    break;
                case TelephonyManager.SIM_STATE_READY:
                    // do something
                    break;
                case TelephonyManager.SIM_STATE_UNKNOWN:
                    // do something
                    break;
            }


如何从SMS获取联系人信息?
ContactItem getContactByAddr(Context context, final SMSItem sms) {  
    Uri personUri = Uri.withAppendedPath(  
            ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);  
    Cursor cur = context.getContentResolver().query(personUri,  
            new String[] { PhoneLookup.DISPLAY_NAME },  
            null, null, null );  
    if( cur.moveToFirst() ) {  
        int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);  
        ContactItem item = new ContactItem();  
        item.mName = cur.getString(nameIdx);  
       cur.close();  
       return item;  
   }  
   return null;  
}


如何在使用gallery在flinging拖动时候不出现选择的情况?
这时候需要注意使用
gallery.setCallbackDuringFling(false)

TabHost组件,怎么调整tab的高度?
TabWidget tabWidget = mTabHost.getTabWidget();
int count = tabWidget.getChildCount();
for(int i = 0;i<count;i++){
        View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);
        view.getLayoutParams().height = 40;
}


如何模拟SDcard?
看图:


应该能看明白。

如何对View截屏?
对于自己的View实现一些绘图或子类化的技术时可以不用系统级这样的方法,我们可以通过
view.setDrawingCacheEnabled(true); //其中View是你需要截图的的View
Bitmap bm = view.getDrawingCache(); 

如何区别AsyncTask和Thread+Handler?
很多网友可能发现Android平台很多应用使用的都是AsyncTask,而并非Thread和Handler去更新UI,这里Android123给大家说下他们到底有什么区别,我们平时应该使用哪种解决方案。从Android 1.5开始系统将AsyncTask引入到android.os包中,过去在很早1.1和1.0 SDK时其实官方将其命名为UserTask,其内部是JDK 1.5开始新增的concurrent库,做过J2EE的网友可能明白并发库效率和强大性,比Java原始的Thread更灵活和强大,但对于轻量级的使用更为占用系统资源。Thread是Java早期为实现多线程而设计的,比较简单不支持concurrent中很多特性在同步和线程池类中需要自己去实现很多的东西,对于分布式应用来说更需要自己写调度代码,而为了Android UI的刷新Google引入了Handler和Looper机制,它们均基于消息实现,有事可能消息队列阻塞或其他原因无法准确的使用。

  Android开发网推荐大家使用AsyncTask代替Thread+Handler的方式,不仅调用上更为简单,经过实测更可靠一些,Google在Browser中大量使用了异步任务作为处理耗时的I/O操作,比如下载文件、读写数据库等等,它们在本质上都离不开消息,但是AsyncTask相比Thread加Handler更为可靠,更易于维护,但AsyncTask缺点也是有的比如一旦线程开启即dobackground方法执行后无法给线程发送消息,仅能通过预先设置好的标记来控制逻辑,当然可以通过线程的挂起等待标志位的改变来通讯,对于某些应用Thread和Handler以及Looper可能更灵活。

如何使多个Drawable叠加(合成图片)?
大家可能知道Bitmap的叠加处理在Android平台中可以通过Canvas一层一层的画就行了,而Drawable中如何处理呢? 除了使用BitmapDrawable的getBitmap方法将Drawable转换为Bitmap外,今天Android123给大家说下好用简单的LayerDrawable类,LayerDrawable顾名思义就是层图形对象。下面直接用一个简单的代码表示:
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);
    Drawable[] array = new Drawable[3];
     array[0] = new PaintDrawable(Color.BLACK); //黑色
     array[1] = new PaintDrawable(Color.WHITE); //白色   
     array[2] = new BitmapDrawable(bm); //位图资源        
    LayerDrawable ld = new LayerDrawable(array); //参数为上面的Drawable数组
    ld.setLayerInset(1, 1, 1, 1, 1);  //第一个参数1代表数组的第二个元素,为白色
    ld.setLayerInset(2, 2, 2, 2, 2); //第一个参数2代表数组的第三个元素,为位图资源
    mImageView.setImageDrawable(ld);

上面的方法中LayerDrawable是关键,Android开发网提示setLayerInset方法原型为public void setLayerInset (int index, int l, int t, int r, int b) 其中第一个参数为层的索引号,后面的四个参数分别为left、top、right和bottom。对于简单的图片合成我们可以将第一和第二层的PaintDrawable换成BitmapDrawable即可实现简单的图片合成。

1 楼 xiaojian623 2011-06-17  
android点滴4
强制保持Android Activity状态
有的时候我们的Android在应用运行时,可能需要临时退出,比如突然接到来电,但是切换回来界面时,可能Activity又重新从第一个界面开始显示,并不是刚才用户操作的界面,这里可以通过在androidmanifest.xml中在需要保留的activity中添加android:alwaysRetainTaskStat="true" 这句即可,这里还要提醒大家的是有时候你的应用可能会产生多个实例,你还可以在主Activity中加入android:launchMode="singleInstance" 来强制让系统仅运行一个实例。

但是还有一种更坏的情况,比如你接的来电时间比较长,由于用户的Android设备RAM较少,你的应用被Java VM的GC给回收了,下次用户再切换回,由于你的应用已经被系统结束了任务,对于游戏来说这可能是致命的。

  所以通过重写Activity的onSaveInstanceState(Bundle outState) 方法可以在Android系统触发结束任务时,保存当前Activity的值,而下次进入该Activity时,可以通过重写 onRestoreInstanceState(Bundle savedInstanceState) 来恢复数据,参数Bundle支持常见的String、Integer、Double、以及字节数组,具体的使用实例可以参考 Android开发网早期文章 onSaveInstanceState和onRestoreInstanceState的用处

Android中string.xml使用总结
http://edison-cool911.iteye.com/blog/1066936

Android应用启动后自动创建桌面快捷方式
某些Android应用安装以后,第一次运行,就会在桌面创建快捷方式。这是如何做到的呢?
public class ShortcutUtil {  
  
    public static void createShortCut(Activity act, int iconResId,  
            int appnameResId) {  
  
        // com.android.launcher.permission.INSTALL_SHORTCUT  
  
        Intent shortcutintent = new Intent(  
                "com.android.launcher.action.INSTALL_SHORTCUT");  
        // 不允许重复创建  
        shortcutintent.putExtra("duplicate", false);  
        // 需要现实的名称  
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,  
                act.getString(appnameResId));  
        // 快捷图片  
        Parcelable icon = Intent.ShortcutIconResource.fromContext(  
                act.getApplicationContext(), iconResId);  
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);  
        // 点击快捷图片,运行的程序主入口  
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,  
                new Intent(act.getApplicationContext(), act.getClass()));  
        // 发送广播  
        act.sendBroadcast(shortcutintent);  
    }  
}  

别忘记增加以下权限,否则看不到任何效果。
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
另外,这样做可能并不友好。更好的做法是,第一次运行程序的时候,提示用户是否创建桌面快捷方式,让用户选择。以后再次运行就不再进行提示了。

模拟按HOME键效果
Android应用开发中, 有一种场景,就是我们不希望用户直接按Back键退出Activity,而是希望应用隐藏到后台,类似于按Home键的效果。
public boolean onKeyDown(int keyCode, KeyEvent event) {  
    if (keyCode == KeyEvent.KEYCODE_BACK) {  
        Intent intent = new Intent(Intent.ACTION_MAIN);  
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
        intent.addCategory(Intent.CATEGORY_HOME);  
        startActivity(intent);  
        return true;  
    }  
    return super.onKeyDown(keyCode, event);  
}  


获取程序的签名
public String getAppSignature(String packname){  
      try {  
          PackageInfo packinfo =pm.getPackageInfo(packname, PackageManager.GET_SIGNATURES);  
          //获取到所有的权限   
          return packinfo.signatures[0].toCharsString();  
  
        } catch (NameNotFoundException e) {  
            e.printStackTrace();  
            return null;  
        }  
}  


获取手机型号,本机电话号码,sdk版本及firmware版本号(即系统版本号)
 TelephonyManager phoneMgr=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
  txtPhoneModel.setText(Build.MODEL); //手机型号
  txtPhoneNumber.setText(phoneMgr.getLine1Number());//本机电话号码
  txtSdkVersion.setText(Build.VERSION.SDK);//SDK版本号
  txtOsVersion.setText(Build.VERSION.RELEASE);//Firmware/OS 版本号

最后,根据Android的安全机制,在使用TelephonyManager时,必须在AndroidManifest.xml中添加<uses-permission android:name="READ_PHONE_STATE" /> 否则无法获得系统的许可。

android隐藏edittext的光标
在EditText之前加这个:
<LinearLayout android:focusable="true"
      android:focusableInTouchMode="true" android:layout_width="0px"
      android:layout_height="0px" />


以下转自:http://407827531.iteye.com/blog/1477962
1.获取屏幕尺寸、密度等信息。
    1)最常用的方法:
        WindowManager windowManager = getWindowManager();   
        Display display = windowManager.getDefaultDisplay();   
        int w = display.getWidth();   
        int h = display.getHeight();
    2)用DisplayMetrics来获得参数:
        DisplayMetrics displayMetrics = new DisplayMetrics() ;
        displayMetrics = getResources().getDisplayMetrics();
        int width = display.getWidth();
        int height = display.getHeight();
        int densityDpi = displayMetrics.densityDpi;
    但是,需要注意的是,在一个低密度的小屏手机上,仅靠上面的代码是不能获取正确的尺寸的。比如说,一部240x320像素的低密度手机,如果运行上述代码,获取到的屏幕尺寸是320x427。因此,研究之后发现,若没有设定多分辨率支持的话,Android系统会将240x320的低密度(120)尺寸转换为中等密度(160)对应的尺寸,这样的话就大大影响了程序的编码。所以,需要在工程的AndroidManifest.xml文件中,加入supports-screens节点,具体的内容如下:
       
<supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:resizeable="true"
            android:anyDensity="true" />

    这样的话,当前的Android程序就支持了多种分辨率,那么就可以得到正确的物理尺寸了。
px与dip转换公式:
pixs =dips * (densityDpi/160). 
dips=(pixs*160)/densityDpi

dp与px转换的方法
public static int dip2px(Context context, float dipValue){
   final float scale = context.getResources().getDisplayMetrics().density;
   return (int)(dipValue * scale +0.5f);
  }
  public static int px2dip(Context context, float pxValue){
   final float scale = context.getResource().getDisplayMetrics().density;
   return (int)(pxValue / scale +0.5f);
  }

2.users-permission的总结:
在编写Android程序时经常会忘记添加权限,下面是网上收集的关于Android uses-permission的资料,方便查找~
android.permission.ACCESS_CHECKIN_PROPERTIES
允许读写访问”properties”表在checkin数据库中,改值可以修改上传( Allows read/write access to the “properties” table in the checkin database, to change values that get uploaded)
android.permission.ACCESS_COARSE_LOCATION
允许一个程序访问CellID或WiFi热点来获取粗略的位置(Allows an application to access coarse (e.g., Cell-ID, WiFi) location)
android.permission.ACCESS_FINE_LOCATION
允许一个程序访问精良位置(如GPS) (Allows an application to access fine (e.g., GPS) location)
android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
允许应用程序访问额外的位置提供命令(Allows an application to access extra location provider commands)
android.permission.ACCESS_MOCK_LOCATION
允许程序创建模拟位置提供用于测试(Allows an application to create mock location providers for testing)
android.permission.ACCESS_NETWORK_STATE
允许程序访问有关GSM网络信息(Allows applications to access information about networks)
android.permission.ACCESS_SURFACE_FLINGER
允许程序使用SurfaceFlinger底层特性(Allows an application to use SurfaceFlinger’s low level features)
android.permission.ACCESS_WIFI_STATE
允许程序访问Wi-Fi网络状态信息(Allows applications to access information about Wi-Fi networks)
android.permission.ADD_SYSTEM_SERVICE
允许程序发布系统级服务(Allows an application to publish system-level services).
android.permission.BATTERY_STATS
允许程序更新手机电池统计信息(Allows an application to update the collected battery statistics)
android.permission.BLUETOOTH
允许程序连接到已配对的蓝牙设备(Allows applications to connect to paired bluetooth devices)
android.permission.BLUETOOTH_ADMIN
允许程序发现和配对蓝牙设备(Allows applications to discover and pair bluetooth devices)
android.permission.BRICK
请求能够禁用设备(非常危险)(Required to be able to disable the device (very *erous!).)
android.permission.BROADCAST_PACKAGE_REMOVED
允许程序广播一个提示消息在一个应用程序包已经移除后(Allows an application to broadcast a notification that an application
package has been removed)
android.permission.BROADCAST_STICKY
允许一个程序广播常用intents(Allows an application to broadcast sticky intents)
android.permission.CALL_PHONE
允许一个程序初始化一个电话拨号不需通过拨号用户界面需要用户确认(Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.)
android.permission.CALL_PRIVILEGED
允许一个程序拨打任何号码,包含紧急号码无需通过拨号用户界面需要用户确认(Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed)
android.permission.CAMERA
请求访问使用照相设备(Required to be able to access the camera device. )
android.permission.CHANGE_COMPONENT_ENABLED_STATE
允许一个程序是否改变一个组件或其他的启用或禁用(Allows an application to change whether an application component (other than its own) is enabled or not. )
android.permission.CHANGE_CONFIGURATION
允许一个程序修改当前设置,如本地化(Allows an application to modify the current configuration, such as locale. )
android.permission.CHANGE_NETWORK_STATE
允许程序改变网络连接状态(Allows applications to change network connectivity state)
android.permission.CHANGE_WIFI_STATE
允许程序改变Wi-Fi连接状态(Allows applications to change Wi-Fi connectivity state)
android.permission.CLEAR_APP_CACHE
允许一个程序清楚缓存从所有安装的程序在设备中(Allows an application to clear the caches of all installed applications on the device. )
android.permission.CLEAR_APP_USER_DATA
允许一个程序清除用户设置(Allows an application to clear user data)
android.permission.CONTROL_LOCATION_UPDATES
允许启用禁止位置更新提示从无线模块(Allows enabling/disabling location update notifications from the radio. )
android.permission.DELETE_CACHE_FILES
允许程序删除缓存文件(Allows an application to delete cache files)
android.permission.DELETE_PACKAGES
允许一个程序删除包(Allows an application to delete packages)
android.permission.DEVICE_POWER
允许访问底层电源管理(Allows low-level access to power management)
android.permission.DIAGNOSTIC
允许程序RW诊断资源(Allows applications to RW to diagnostic resources. )
android.permission.DISABLE_KEYGUARD
允许程序禁用键盘锁(Allows applications to disable the keyguard )
android.permission.DUMP
允许程序返回状态抓取信息从系统服务(Allows an application to retrieve state dump information from system services.)
android.permission.EXPAND_STATUS_BAR
允许一个程序扩展收缩在状态栏,android开发网提示应该是一个类似Windows Mobile中的托盘程序(Allows an application to expand or collapse the status bar. )
android.permission.FACTORY_TEST
作为一个工厂测试程序,运行在root用户(Run as a manufacturer test application, running as the root user. )
android.permission.FLASHLIGHT
访问闪光灯,android开发网提示HTC Dream不包含闪光灯(Allows access to the flashlight )
android.permission.FORCE_BACK
允许程序强行一个后退操作是否在顶层activities(Allows an application to force a BACK operation on whatever is the top activity. )
android.permission.FOTA_UPDATE
暂时不了解这是做什么使用的,android开发网分析可能是一个预留权限.
android.permission.GET_ACCOUNTS
访问一个帐户列表在Accounts Service中(Allows access to the list of accounts in the Accounts Service)
android.permission.GET_PACKAGE_SIZE
允许一个程序获取任何package占用空间容量(Allows an application to find out the space used by any package. )
android.permission.GET_TASKS
允许一个程序获取信息有关当前或最近运行的任务,一个缩略的任务状态,是否活动等等(Allows an application to get information about the currently or recently running tasks: a thumbnail representation of the tasks, what activities are running in it, etc.)
android.permission.HARDWARE_TEST
允许访问硬件(Allows access to hardware peripherals. )
android.permission.INJECT_EVENTS
允许一个程序截获用户事件如按键、触摸、轨迹球等等到一个时间流,android 开发网提醒算是hook技术吧(Allows an application to inject user events (keys, touch, trackball) into the event stream and deliver them to ANY window.)
android.permission.INSTALL_PACKAGES
允许一个程序安装packages(Allows an application to install packages. )
android.permission.INTERNAL_SYSTEM_WINDOW
允许打开窗口使用系统用户界面(Allows an application to open windows that are for use by parts of the system user interface. )
android.permission.INTERNET
允许程序打开网络套接字(Allows applications to open network sockets)
android.permission.MANAGE_APP_TOKENS
允许程序管理(创建、催后、 z- order默认向z轴推移)程序引用在窗口管理器中(Allows an application to manage (create, destroy, Z-order) application tokens in the window manager. )
android.permission.MASTER_CLEAR
目前还没有明确的解释,android开发网分析可能是清除一切数据,类似硬格机
android.permission.MODIFY_AUDIO_SETTINGS
允许程序修改全局音频设置(Allows an application to modify global audio settings)
android.permission.MODIFY_PHONE_STATE
允许修改话机状态,如电源,人机接口等(Allows modification of the telephony state – power on, mmi, etc. )
android.permission.MOUNT_UNMOUNT_FILESYSTEMS
允许挂载和反挂载文件系统可移动存储(Allows mounting and unmounting file systems for removable storage. )
android.permission.PERSISTENT_ACTIVITY
允许一个程序设置他的activities显示(Allow an application to make its activities persistent. )
android.permission.PROCESS_OUTGOING_CALLS
允许程序监视、修改有关播出电话(Allows an application to monitor, modify, or abort outgoing calls)
android.permission.READ_CALENDAR
允许程序读取用户日历数据(Allows an application to read the user’s calendar data.)
android.permission.READ_CONTACTS
允许程序读取用户联系人数据(Allows an application to read the user’s contacts data.)
android.permission.READ_FRAME_BUFFER
允许程序屏幕波或和更多常规的访问帧缓冲数据(Allows an application to take screen shots and more generally get access to the frame buffer data)
android.permission.READ_INPUT_STATE
允许程序返回当前按键状态(Allows an application to retrieve the current state of keys and switches. )
android.permission.READ_LOGS
允许程序读取底层系统日志文件(Allows an application to read the low-level system log files. )
android.permission.READ_OWNER_DATA
允许程序读取所有者数据(Allows an application to read the owner’s data)
android.permission.READ_SMS
允许程序读取短信息(Allows an application to read SMS messages.)
android.permission.READ_SYNC_SETTINGS
允许程序读取同步设置(Allows applications to read the sync settings)
android.permission.READ_SYNC_STATS
允许程序读取同步状态(Allows applications to read the sync stats)
android.permission.REBOOT
请求能够重新启动设备(Required to be able to reboot the device. )
android.permission.RECEIVE_BOOT_COMPLETED
允许一个程序接收到 ACTION_BOOT_COMPLETED广播在系统完成启动(Allows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting. )
android.permission.RECEIVE_MMS
允许一个程序监控将收到MMS彩信,记录或处理(Allows an application to monitor incoming MMS messages, to record or perform processing on them. )
android.permission.RECEIVE_SMS
允许程序监控一个将收到短信息,记录或处理(Allows an application to monitor incoming SMS messages, to record or perform processing on them.)
android.permission.RECEIVE_WAP_PUSH
允许程序监控将收到WAP PUSH信息(Allows an application to monitor incoming WAP push messages. )
android.permission.RECORD_AUDIO
允许程序录制音频(Allows an application to record audio)
android.permission.REORDER_TASKS
允许程序改变Z轴排列任务(Allows an application to change the Z-order of tasks)
android.permission.RESTART_PACKAGES
允许程序重新启动其他程序(Allows an application to restart other applications)
android.permission.SEND_SMS
允许程序发送SMS短信(Allows an application to send SMS messages)
android.permission.SET_ACTIVITY_WATCHER
允许程序监控或控制activities已经启动全局系统中(Allows an application to watch and control how activities are started globally in the system.)
android.permission.SET_ALWAYS_FINISH
允许程序控制是否活动间接完成在处于后台时(Allows an application to control whether activities are immediately finished when put in the background.)
android.permission.SET_ANIMATION_SCALE
修改全局信息比例(Modify the global animation scaling factor.)
android.permission.SET_DEBUG_APP
配置一个程序用于调试(Configure an application for debugging.)
android.permission.SET_ORIENTATION
允许底层访问设置屏幕方向和实际旋转(Allows low-level access to setting the orientation (actually rotation) of the screen.)
android.permission.SET_PREFERRED_APPLICATIONS
允许一个程序修改列表参数PackageManager.addPackageToPreferred()和 PackageManager.removePackageFromPreferred()方法(Allows an application to modify the list of preferred applications with the PackageManager.addPackageToPreferred() and PackageManager.removePackageFromPreferred() methods.)
android.permission.SET_PROCESS_FOREGROUND
允许程序当前运行程序强行到前台(Allows an application to force any currently running process to be in the foreground.)
android.permission.SET_PROCESS_LIMIT
允许设置最大的运行进程数量(Allows an application to set the maximum number of (not needed) application processes that can be running. )
android.permission.SET_TIME_ZONE
允许程序设置时间区域(Allows applications to set the system time zone)
android.permission.SET_WALLPAPER
允许程序设置壁纸(Allows applications to set the wallpaper )
android.permission.SET_WALLPAPER_HINTS
允许程序设置壁纸hits(Allows applications to set the wallpaper hints)
android.permission.SIGNAL_PERSISTENT_PROCESSES
允许程序请求发送信号到所有显示的进程中(Allow an application to request that a signal be sent to all persistent processes)
android.permission.STATUS_BAR
允许程序打开、关闭或禁用状态栏及图标Allows an application to open, close, or disable the status bar and its icons.
android.permission.SUBSCRIBED_FEEDS_READ
允许一个程序访问订阅RSS Feed内容提供(Allows an application to allow access the subscribed feeds ContentProvider. )
android.permission.SUBSCRIBED_FEEDS_WRITE
系统暂时保留改设置,android开发网认为未来版本会加入该功能。
android.permission.SYSTEM_ALERT_WINDOW
允许一个程序打开窗口使用 TYPE_SYSTEM_ALERT,显示在其他所有程序的顶层(Allows an application to open windows using the type TYPE_SYSTEM_ALERT, shown on top of all other applications. )
android.permission.VIBRATE
允许访问振动设备(Allows access to the vibrator)
android.permission.WAKE_LOCK
允许使用PowerManager的 WakeLocks保持进程在休眠时从屏幕消失( Allows using PowerManager WakeLocks to keep
processor from sleeping or screen from dimming)
android.permission.WRITE_APN_SETTINGS
允许程序写入API设置(Allows applications to write the apn settings)
android.permission.WRITE_CALENDAR
允许一个程序写入但不读取用户日历数据(Allows an application to write (but not read) the user’s calendar data. )
android.permission.WRITE_CONTACTS
允许程序写入但不读取用户联系人数据(Allows an application to write (but not read) the user’s contacts data. )
android.permission.WRITE_GSERVICES
允许程序修改Google服务地图(Allows an application to modify the Google service map. )
android.permission.WRITE_OWNER_DATA
允许一个程序写入但不读取所有者数据(Allows an application to write (but not read) the owner’s data.)
android.permission.WRITE_SETTINGS
允许程序读取或写入系统设置(Allows an application to read or write the system settings. )
android.permission.WRITE_SMS
允许程序写短信(Allows an application to write SMS messages)
android.permission.WRITE_SYNC_SETTINGS
允许程序写入同步设置(Allows applications to write the sync settings)
3.空间置顶:永远保留在最顶层,类似于天天动听的桌面歌词那样,始终在最顶层。
API中有这样一个常量:WindowManager.LayoutParams.TYPE_SYSTEM_ALERT。
文档中对它的的描述为:“Window type: system window, such as low power alert. These windows are always on top of application windows.”也就是说用这个type可以显示在其他application的顶层,但注意:当用到这个常量的时候,要加上相应的权限,即:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />。
这个权限在文档中的描述为:“Allows an application to open windows using the type TYPE_SYSTEM_ALERT, shown on top of all other applications. Very few applications should use this permission; these windows are intended for system-level interaction with the user.”
WindowManager mWin = (WindowManager)getSystemService(Context.WINDOW_SERVICE)
然后使用addView的方法创建窗体,这样的窗体时凌驾于任何程序之上的。
4.设置全屏和无标题: 在实际的应用程序开发中,我们有时需要把 Activity 设置成全屏显示,一般情况下,可以通过两种方式来设置全屏显示效果。其一,通过在代码中可以设置,其二,通过manifest配置文件来设置全屏。
其一:在代码中设置(如下)
 public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
          
        //设置无标题  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //设置全屏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  
          
        setContentView(R.layout.main);  
 }  

但要注意的是:在代码中设置的话,设置无标题和设置全屏的两段代码要放置在 setContentView(R.layout.main); 这段代码的前面。要不然会报错。
    其二:在manifest配置文件中设置
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
      package="com.andyidea"  
      android:versionCode="1"  
      android:versionName="1.0">  
    <uses-sdk android:minSdkVersion="8" />  
    <application android:icon="@drawable/icon" android:label="@string/app_name">  
        <activity android:name=".login.LoginActivity"   
                  android:theme="@android:style/android.NoTitleBar.Fullscreen"  
                  android:label="@string/app_name">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
    </application>  
 </manifest>

在相应的Activity中节点中添加属性:android:theme="@android:style/Theme.NoTitleBar.Fullscreen" 即可以设置某个Activity全屏显示。若设置成         android:theme="@android:style/Theme.NoTitleBar" 即是只是设置成无标题状态。
5.在代码中设置背景:
  
Resources res = getResources();
      Drawable drawable = res.getDrawable(R.drawable.bkcolor);
      this.getWindow().setBackgroundDrawable(drawable);

  需要在value目录下的string.xml文件中加入一段代码,如<drawable name="bkcolor">#ff00ff</drawable>
6.在ondraw中获取text文本的长和宽:
  1)字符串宽度 Paint.measureText 方法,这个方法很简单。
  2)字符高度使用 FontMetrics 类:
  
Paint pFont = new Paint();
  Rect rect = new Rect();
  //返回包围整个字符串的最小的一个Rect区域
  pFont.getTextBounds(str, 0, 1, rect);
  strwid = rect.width();
  strhei = rect.height();

7.抗锯齿:在画图时,由于旋转或者缩放后,会产生锯齿,可以通过这样解决。
  1)直接在paint上加上抗锯齿
       paint.setAntiAlias(true);
  2)在不能给paint加抗锯齿的地方,可以直接给canvas加抗锯齿
    canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
1 楼 a295481541 2012-04-09  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值