[Android]调用字符串资源的几种方法

字符串资源的定义

文件路径:res/values/strings.xml

字符串资源定义示例:

<? xmlversion="1.0"encoding="utf-8" ?>
< resources >
< string name ="hello" > Hello! </ string >
</ resources >

字符串资源的调用

在 Layout XML 调用字符串资源:

< TextView
android:layout_width ="fill_parent"
android:layout_height
="wrap_content"
android:text
="@string/hello" />

在 Activity 获取字符串资源:

this .getString(R.string.hello)

从 Context 获取字符串资源:

context.getString(R.string.hello)

从 Application 获取字符串资源:

application.getString(R.string.hello)


[android]android中使用代码混淆出现Conversion to Dalvik format failed with error 1错误的解决办法
lrenwang 2012/01/26
[android]webview设置屏幕密度 lrenwang 2011/12/27
[android]Android 常用代码大集合 lrenwang 2011/11/07
[android]JSON与android lrenwang 2011/08/04
[android]Android的计量单位px,in,mm,pt,dp,dip,sp lrenwang 2011/05/19
[android]android权限列表 lrenwang 2011/05/05
[android]Android AlertDialog类的几个简单实例 lrenwang 2011/05/05
[android]android数组对象操作 lrenwang 2011/05/04
[android]Android内置的SQLite操作方法 lrenwang 2011/05/03
[android]判断Android手机是否联网 lrenwang 2011/04/26
[android]android权限列表 lrenwang 2011/04/26
[android]android 铃声位置 lrenwang 2011/02/08
[android]HTC G7 短信时间不正确 lrenwang 2011/01/21
[android]android开机自动运行 lrenwang 2010/11/24
[android]Android访问php取回json数据 lrenwang 2010/11/16
分页: 1/212[ 显示模式: 摘要| 列表]

Android <Android应用开发实战> 资源类型<一>

1.字符串资源
>>1.普通字符串
>>2.字符串数组

<resources>    <string-array name="planets_array">        <item>aaa</item>        <item>bbb</item>    </string-array></resources>

获取方式:getResources().getStringArray(R.array.planets_array)
>>3.复数字符串资源
某些自然语言中,不同的数字在使用方法上会有所不同,比如one book,two books。当数量大于1时,会使用不同的名词或其它复数形式;

<resources>    <plurals name="numberOfp">        <item quantity="one">one person</item>        <item quantity="other">more persons</item>    </plurals></resources>

quantity属性的值除了one和other外,还可以是zero,two,few,many;
引用复数字符串:
// 引用数字为1的复数字符串
getResources().getQuantityString(R.pluarlas.numberOfp,1);
// 引用数字为其它值的复数字符串
getResources().getQuantityString(R.pluarlas.numberOfp,10,10);
>>4.占位符格式化字符串
常用的格式化字符串三种方法:
  >>1.在字符串中使用引号
字符串中的值虽然可以随意指定,但是当遇到特殊符号时(双引号,单引号)就需要采取特殊的方法来处理这些符号。
如果是单引号(')可以使用转义符(\)或用双引号(")将整个字符串括起来,如果是双引号,可以在双引号前使用转义符(\)。

<resources>    <string name="str1">"This'll work"</string> This'll work    <string name="str2">This\'ll work</string> This'll work    <string name="str3">\"apple\"</string> "apple"</resources>

  >>2.用占位符格式化字符串
使用String.format(String,Object...)方法可以格式化带占位符的字符串,只需要在字符串中插入占位符,就可以使用String.format方法格式化字符串资源,format方法要求的占位符用%1,%,...,%n,其实第n个占位符与format方法的n+1个参数值对应;

<resources>    <!-- $s表示该占位符被字符串替换,$d表示该占位符被整数替换 -->    <string name="str1">hello,%1$s!You have %2$d new message</string></resources>

String str1 =String.format(getResources().getString(R.string.str1), "ly", 17);
  >>3.使用HTML标签格式化字符串资源

字符串资源支持一些HTML标签,因此可以直接在字符串资源中使用这些HTML标签格式化字符串
字符串资源支持如下的HTML标签
<b>粗体字
<i>斜体定
<u>带下划线的字
有时需要同时使用HTML标签和占位符格式化字符串,如果使用String.format方法格式化字符串,会忽略字符串中的所有HTML标签。为了使format方法可以格式化带
HTML标签的确字符,需要使用Html.formHTML方法处理字符串;

<resources>    <string name="hello_world">Welcome to <b>android</b></string>    <string name="str2">Hello,%1$s! You have &lt;b> %2d new messages &lt;/b></string> <!--同时包含占位符和html标签的字符串--></resources>

由于需要使用Html.formHTML方法处理字符串,因此HTML标签中的 "<" 需要使用 "&lt;" 表示 ">" 并不需要处理
获取字符串:

String text = String.format(getResources().getString(R.string.str2), "ly", 10);CharSequence styledText = Html.fromHtml(text);
// 如果format的某个参数包含HTML的特殊字符,如"<","&",可以使用如下方式读取字符串的值;String escapedUsername
= TextUtils.htmlEncode("");String text1 = String.format(getResources().getString(R.string.str2), "ly", 20);

2.Layout资源
1、如果根节点是View,除了<requestFocus>标签外,不能添加任何子标签,<requestFocus>可能被添加到布局文件的任何View中,表示该标签对应的控件在显示时处于焦点状态,整个布局文件只能有一个<requestFocus>标签
2、根节点是ViewGroup,常用的布局都是ViewGroup的子类
3、重用布局文件
如果想重用某个布局文件,可以使用<include>标签
<include layout="@layout/xx_layout" />
如果想让一个布局文件被另一个布局文件引用(使用<include>标签),可以使用<merge>作为被引用布局文件的根节点,由于<merge>并不会生成任何标签(在大量引用布局文件时不至于生成大量无用的标签),但是xml文件必须要有一个根节点,因此<merge>所起的作用就是作为xml文件的根节点,以使xml文件在编译时不至于出错,可以把<merge>当成<FrameLayout>使用;

3.图像资源
在图像资源中可以存储图像文件,还可以使用xml格式的图像资源来控件图像的状态和行为;
>>1.普通图像资源
Drawable da = getResources().getDrawable(R.drawable.xxx);

>>2.xml图像资源
xml图像资源其实就是在drawable目录中指定的xml文件,此种方式可以额外指定图像的某些属性,如图像拉动、排列方式;

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"    android:src="@drawable/ic_launcher"    android:tileMode="repeat" ></bitmap>

>>3.Nine-Patch图像资源
Nine-Patch图像资源文件必须以9.png作为文件扩展名,如abc.9.png
该图像资源的主要作用是:防止图像的某一部分被拉伸;确定将图像作为背景图的控件中内容显示的位置;
Android SDK本身提供了一个Draw 9-patch的工具,启动<sdk目录>\tools\draw9patch.bat命令启动该工具;
可以通过此工具在png图的四周绘制1个像素粗的直线,上边缘和左边缘的直线分别表示图像在水平和垂直方向可位值的范围。如果水平或垂直方向的某个区域不需要拉伸,则可不绘制相应的直线;右边缘和下边缘的直线分别表示图像所在控件中内容的显示范围,内容只在右边缘和下边缘绘制直线的区域显示,表示内容显示范围和拉伸范围的两给直线有一个重要区别就是表示内容显示范围的直线中间不能断开,而表示拉伸范围的直线中间可以断开;
Nine-Patch图像资源与普通图像资源引用方法相同,在引用时只写文件名,活力.9.png;

>>4.XML Nine-Patch图像资源
Nine-Patch图像资源也有与其对应的xml图像资源,使用<nine-patch>标签来引用Nine-Patch格式的图像,有一个设置抖动的android:dither属性;

>>5.图层资源
图层资源类似于<FrameLayout>不同的是<FrameLayout>标签中可以包含任意的控件,而图层资源每一层都只有是图像,定义图层资源必须使用<layer-list>作为资源文件的根节点,<layer-list>标签中包含多个<item>标签,每一个标签表示一个图像,最后一个<item>标签显示在最顶层;
默认情况下,图像会尽量充满显示图像的范围,图像可能会有拉伸,为了避免图像拉伸,可以在<item>标签中使用<bitmap>标签引用图像;

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:bottom="10dip" 底端偏移的像素        android:left="10dip" 左侧偏移的像素        android:right="10dip" ...        android:top="10dip"> ...        <bitmap            android:gravity="center"            android:src="@drawable/hell" />    </item></layer-list>

某些情况下,可以使用图层来代替<FrameLayout>

>>6.图像状态资源,处理控件不同状态下的显示状态

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/bm" android:state_focused="true"></item>    <item android:drawable="@drawable/bm" android:state_pressed="true"></item>    <item android:drawable="@drawable/bm"></item></selector>
// android:state_focused/pressed设置为true表示当前item的drawable属性为获取焦点和按下时的drawable样式

>>7.图像级别(Level)资源
图像资源状态只能指定几种有限的状态,可以通过图像级别指定更多的状态;图像级别是一个整数的区间,可以通过ImageView.setImageLevel或Drawable.setLevel方法切换不同状态的图像;图像级别资源是xml文件,必须以<level-list>为根节点,每一个item表示一个级别区间,下面是一个xml文件;通过ImageView.setImageLevel(level),根据level所在的区间设定显示的图像资源,如果level不在任一区间内则清空ImageView当前图像;

<level-list xmlns:android="http://schemas.android.com/apk/res/android">    <item android:maxLevel="2" android:minLevel="0" android:drawable="@drawable/hell" />    <item android:maxLevel="4" android:minLevel="3" android:drawable="@drawable/hell" /></level-list>

>>8.淡入淡出(Cross-fade)资源
也是切换两个图像(不支持多于两个图像的切换),并且使这两个图像以淡入淡出效果进行切换,如电灯在开关时逐渐变亮或逐渐变暗;

<transition xmlns:android="http://schemas.android.com/apk/res/android" >    <item android:drawable="@drawable/hell"/>    <item android:drawable="@drawable/hell"/></transition>

        TransitionDrawable da = ...;        // 从第一张图片切换到第二张图片,时间效果为1秒        da.startTransition(1000);        // 从第二张图片切换到第一张图片,时间效果为1秒        da.reverseTransition(1000);

>>9.嵌入(insert)图像资源
使用场景:要显示的图像要求要小于装载图像的View(图小于View区域),也是通过xml资源定义,只有一个节点inset。

<inset xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/hell"    android:insetLeft="10dip" > <!--图像距离左边的距离,延伸-->上/下/右的距离--></inset>

>>10.剪切(Clip)图像资源,使用剪切图像资源可以只显示图像的一部分,如可以通过此来制作进度条;

<clip xmlns:android="http://schemas.android.com/apk/res/android"    android:clipOrientation="horizontal" // 指定截取的方向    android:drawable="@drawable/hell" // 指定要截取的图像    android:gravity="left" > // 指定截取的方式,在此为从左侧开始截取</clip>
        ClipDrawable cd = ...;        cd.setLevel(1000);

上面ClipDrawable.setLevel(level)设置截取的图像宽度,ClipDrawable预设了最大值10000(表示不进行截取),最小值为0(表示不显示);

>>11. 比例(Scale)图像资源

<scale xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/hell"    android:scaleGravity="center" // 设置图像显示的位置    android:scaleHeight="70%" // 设置图像显示的高度    android:scaleWidth="80%" > // 设置图像显示的宽度</scale>

>>12.形状资源

<shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle" > shape可以指定就矩形,oval(椭圆),line(直线),ring(圆)    <corners> 定义圆角    </corners>    <gradient        android:angle="45"        android:startColor="#000000"        android:endColor="#FFFFFF" > 定义颜色渐变,从左下角到或上角    </gradient>    <padding> 定义控件内容到边框的距离    </padding>    <stroke> 定义边线    </stroke>    <solid> 定义填充    </solid>    <size> 定义大小    </size></shape>

分类: Android 资源类型 标签: Android 资源类型

getSystemService是Android很重要的一个API,它是Activity的一个方法,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。

传入的Name 返回的对象 说明
WINDOW_SERVICE WindowManager 管理打开的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定义的view
ACTIVITY_SERVICE ActivityManager 管理应用程序的系统状态

POWER_SERVICE

PowerManger 电源的服务
ALARM_SERVICE AlarmManager 闹钟的服务

NOTIFICATION_SERVICE

NotificationManager 状态栏的服务
KEYGUARD_SERVICE KeyguardManager 键盘锁的服务
LOCATION_SERVICE LocationManager 位置的服务,如GPS
SEARCH_SERVICE SearchManager 搜索的服务
VEBRATOR_SERVICE Vebrator 手机震动的服务
CONNECTIVITY_SERVICE Connectivity 网络连接的服务
WIFI_SERVICE WifiManager Wi-Fi服务
TELEPHONY_SERVICE TeleponyManager 电话服务

<pre>1、系统服务(以下代码有一些规律:大部分的XXXManager都是使用Context的getSystemService方法实例化的)
1.1 实例化ActivityManager及权限配置
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.GET_TASKS"/&gt;
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
1.2 实例化AlarmManager
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1.3 实例化AudioManager
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1.4 实例化ClipboardManager
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
1.5 实例化ConnectivityManager
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
1.6 实例化InputMethodManager
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1.7 实例化KeyguardManager
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
1.8 实例化LayoutInflater
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
1.9 实例化LocationManager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
1.10 实例化NotificationManager
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
1.11 实例化PowerManager
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.DEVICE_POWER"/&gt;
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
1.12 实例化SearchManager
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1.13 实例化SensorManager
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
1.14 实例化TelephonyManager及权限配置
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.READ_PHONE_STATE"/&gt;
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
1.15 实例化Vibrator及权限配置
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.VIBRATE"/&gt;
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
1.16 实例化WallpaperService
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.SET_WALLPAPER"/&gt;
WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE);
1.17 实例化WifiManager
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/&gt;
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
1.18 实例化WindowManager
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
2. 基本操作
2.1 发送短信及其权限配置
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.SEND_SMS"/&gt;
SmsManager m = SmsManager.getDefault();
String destinationNumber = "0123456789";
String text = "Hello, MOTO!";
m.sendTextMessage(destinationNumber, null, text, null, null);
2.2 显示一个Toast
Toast.makeText(this, "Put your message here", Toast.LENGTH_SHORT).show();
2.3 显示一个通知
int notificationID = 10;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create the notification
Notification notification = new Notification(R.drawable.yourIconId, "Put your notification text here", System.currentTimeMillis());
// Create the notification expanded message
// When the user clicks on it, it opens your activity
Intent intent = new Intent(this, YourActivityName.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "Put your title here", "Put your text here", pendingIntent);
// Show notification
notificationManager.notify(notificationID, notification);
2.4 使手机震动及权限配置
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.VIBRATE"/&gt;
// Vibrate for 1000 miliseconds
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
2.5 间歇震动及权限配置
// AndroidManifest.xml must have the following permission:
//&lt;uses-permission android:name="android.permission.VIBRATE"/&gt;
// Vibrate in a Pattern with 0ms off(start immediately), 200ms on, 100ms off, 100ms on, 500ms off, 500ms on,
// repeating the pattern starting from index 4 - 100ms on.
// Note that you'll have to call vibrator.cancel() in order to stop vibrator.
// Change second parameter to -1 if you want play the pattern only once.
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(new long[] {0, 200, 100, 100, 500, 500}, 4);
3. 数据库相关
3.1 打开或创建一个数据库
SQLiteDatabase db =openOrCreateDatabase("MyDatabaseName", MODE_PRIVATE, null);
3.2 删除一个数据库
boolean success = deleteDatabase("MyDatabaseName");
3.3 创建表
db.execSQL("CREATE TABLE MyTableName (_id INTEGER PRIMARY KEY AUTOINCREMENT, YourColumnName TEXT);");
3.4 删除表
db.execSQL("DROP TABLE IF EXISTS MyTableName");
3.5 添加数据
// Since SQL doesn't allow inserting a completely empty row, the second parameter of db.insert defines the column that will receive NULL if cv is empty
ContentValues cv=new ContentValues();
cv.put("YourColumnName", "YourColumnValue");
db.insert("MyTableName", "YourColumnName", cv);
3.6 更新数据
ContentValues cv=new ContentValues();
cv.put("YourColumnName", "YourColumnValue");
db.update("MyTableName", cv, "_id=?", new String[]{"1"});
3.7 删除数据
db.delete("MyTableName","_id=?", new String[]{"1"});
3.9 查询
Cursor c=db.rawQuery(SQL_COMMAND, null);
4. 创建菜单
4.1 创建选项菜单
/*
* Add this in your Activity
*/
private final int MENU_ITEM_0 = 0;
private final int MENU_ITEM_1 = 1;


/**
* Add menu items
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ITEM_0, 0, "Menu Item 0");
menu.add(0, MENU_ITEM_1, 0, "Menu Item 1");
return true;
}


/**
* Define menu action
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_0:
// put your code here
break;
case MENU_ITEM_1:
// put your code here
break;
default:
// put your code here
}
return false;
}
4.2 使菜单失效
menu.findItem("yourItemId").setEnabled(false);
4.3 添加子菜单
SubMenu subMenu = menu.addSubMenu("YourMenu");
subMenu.add("YourSubMenu1");
4.4 使用XML创建菜单
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
&lt;item android:id="@+id/menu_0"
android:title="Menu Item 0" /&gt;
&lt;item android:id="@+id/menu_1"
android:title="Menu Item 1" /&gt;
&lt;/menu&gt;
4.5 实例化XML菜单
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourXMLName, menu);
return true;
}
5. 对话框
5.1 警告对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Put your question here?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// put your code here
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// put your code here
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
5.2 进度条对话框
ProgressDialog dialog = ProgressDialog.show(this, "Your Title",
"Put your message here", true);


ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(PROGRESS_MAX);
progressDialog.setMessage("Put your message here");
progressDialog.setCancelable(false);
progressDialog.incrementProgressBy(PROGRESS_INCREMENT);
5.3 日期选择对话框
// Define the date picker dialog listener, which will be called after
// the user picks a date in the dialog displayed
DatePickerDialog.OnDateSetListener datePickerDialogListener =
new DatePickerDialog.OnDateSetListener() {


public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// put your code here
// update your model/view given with the date selected by the user
}
};


// Get the current date
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);


// Create Date Picker Dialog
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
datePickerDialogListener,
year, month, day);


// Display Date Picker Dialog
datePickerDialog.show();
5.4 时间选择对话框
// Define the date picker dialog listener, which will be called after
// the user picks a time in the dialog displayed
TimePickerDialog.OnTimeSetListener timePickerDialogListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// put your code here
// update your model/view given with the date selected by the user
}
};


// Get the current time
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);


// Create Time Picker Dialog
TimePickerDialog timerPickerDialog = new TimePickerDialog(this,
timePickerDialogListener, hour, minute, false);


// Display Time Picker Dialog
timerPickerDialog.show();
5.5 自定义对话框
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.yourLayoutId);
dialog.show();
5.6 自定义警告对话框
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.yourLayoutId, (ViewGroup) findViewById(R.id.yourLayoutRoot));
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setView(layout);
AlertDialog alertDialog = builder.create();
alertDialog.show();
6. 屏幕相关
6.1 全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
6.2 获得屏幕大小
Display display = ((WindowManager)
getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
6.3 获得屏幕方向
Display display = ((WindowManager)
getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
7. GPS 相关
7.1 获得当前经纬度坐标
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
}
public void onProviderEnabled(String provider) {
// called when the provider is enabled by the user
}
public void onProviderDisabled(String provider) {
// called when the provider is disabled by the user, if it's already disabled, it's called immediately after requestLocationUpdates
}


public void onLocationChanged(Location location) {
double latitute = location.getLatitude();
double longitude = location.getLongitude();
// do whatever you want with the coordinates
}
});
7.2 获得最后经纬度
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitute, longitude = 0;
if(location != null){
latitute = location.getLatitude();
longitude = location.getLongitude();
}
7.3 计算两点之间的距离
Location originLocation = new Location("gps");
Location destinationLocation = new Location("gps");
originLocation.setLatitude(originLatitude);
originLocation.setLongitude(originLongitude);
destinationLocation.setLatitude(originLatitude);
destinationLocation.setLongitude(originLongitude);
float distance = originLocation.distanceTo(destinationLocation);
7.4 监听GPS状态
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.addGpsStatusListener(new GpsStatus.Listener(){


public void onGpsStatusChanged(int event) {
switch(event){
// Event sent when the GPS system has started
case GpsStatus.GPS_EVENT_STARTED:
// put your code here
break;


// Event sent when the GPS system has stopped
case GpsStatus.GPS_EVENT_STOPPED:
// put your code here
break;


// Event sent when the GPS system has received its first fix since starting
case GpsStatus.GPS_EVENT_FIRST_FIX:
// put your code here
break;


// Event sent periodically to report GPS satellite status
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
// put your code here
break;


}
}
});
7.5 注册一个GPS警告
// AndroidManifest.xml must have the following permission:
// &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt;
// Use PendingIntent.getActivity(Context, int, Intent, int), PendingIntent.getBroadcast(Context, int, Intent, int) or PendingIntent.getService(Context, int, Intent, int) to create the PendingIntent, which will be used to generate an Intent to fire when the proximity condition is satisfied.
PendingIntent pendingIntent;
// latitudethe latitude of the central point of the alert region
// longitudethe longitude of the central point of the alert region
// radiusthe radius of the central point of the alert region, in meters
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.addProximityAlert(latitude, longitude, radius, -1, pendingIntent);
7.6 未完待续...</pre>

Android 常用代码大集合

lrenwang, 2011/11/07 10:52 , android, 评论(0), 阅读(1325), Via 本站原创 大|中|小 1 活动管理器
权限 <uses-permission android:name="android.permission.GET_TASKS"/>
代码 ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

2 警报管理器 权限
代码 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

3 音频管理器 权限
代码 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
4 剪贴板管理器 权限
代码 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

5 连接管理器 权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
代码 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVIT

6 输入法管理器 权限
代码 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_S)
7 键盘管理器 权限
代码 KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

8 布局解压器管理器 权限
代码 LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

9 位置管理器 权限
代码 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

10 通知管理器 权限
代码 NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATIO)

11 电源管理器 权限 <uses-permission android:name="android.permission.DEVICE_POWER"/>
代码 PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

12 搜索管理器 权限
代码 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

13 传感器管理器 权限
代码 SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

14 电话管理器 权限 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
代码 TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

15 振动器 权限 <uses-permission android:name="android.permission.VIBRATE"/>
代码 Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

16 墙纸 权限 <uses-permission android:name="android.permission.SET_WALLPAPER"/>
代码 WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE);

17 Wi-Fi管理器 权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
代码 WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

18 窗口管理器 权限
代码 WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

19获取用户android手机 机器码和手机号

TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  String imei = tm.getDeviceId();//获取机器码
   String tel = tm.getLine1Number();//获取手机号
20设置为横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
21无标题栏、全屏

//无标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);//要在setcontentView之前哦
//全屏模式
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);


22 获取屏幕宽高

DisplayMetrics dm = new DisplayMetrics();
//获取窗口属性
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;//320
int screenHeight = dm.heightPixels;//480


23使用样式表
在 res/values下面新建一个XML文件style.xml ,然后写下如下代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="style1">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#EC9237</item>
</style>
<style name="style2"><item name="android:textSize">10sp</item>
<item name="android:textColor">#FF9237</item>
</style>
</resources>

使用:
<TextView
style="@style/style1"//调用style
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="样式1"
android:id="@+id/Tv1">
</TextView>

24使用布局文件,切换 布局
建立两个布局文件
在事件里面写代码

@Override
public void onClick(View v) {
helllo.this.setContentView(R.layout.layout2);
Button tempBtn=(Button)findViewById(R.id.btn_click1);
tempBtn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
helllo.this.setContentView(R.layout.xxx);
}
});


=========================================================================
1.Intent用法
2010-04-27 12:09



Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);
2. 向下一个Activity传递数据(使用Bundle和Intent.putExtras)
Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle=new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle); // it.putExtra(“test”, "shuju”);
startActivity(it); // startActivityForResult(it,REQUEST_CODE);
对于数据 的获取可以采用:
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");
3. 向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动 的Activity)
Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString("name", "This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);
4. 回调上一个Activity的结果处理函数(onActivityResult)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE){
if(resultCode==RESULT_CANCELED)
setTitle("cancle");
else if (resultCode==RESULT_OK) {
String temp=null;
Bundle bundle=data.getExtras();
if(bundle!=null) temp=bundle.getString("name");
setTitle(temp);
}
}
}
显示网页
1. Uri uri = Uri.parse("http://google.com");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
显示地图
1. Uri uri = Uri.parse("geo:38.899533,-77.036476");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
4. //其他 geo URI 範例
5. //geo:latitude,longitude
6. //geo:latitude,longitude?z=zoom
7. //geo:0,0?q=my+street+address
8. //geo:0,0?q=business+near+city
9. //google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom
路 径规划
1. Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
4. //where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456
打 电话
1. //叫出拨号程序
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_DIAL, uri);
4. startActivity(it);
1. //直接打电话出去
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_CALL, uri);
4. startActivity(it);
5. //用這個,要在 AndroidManifest.xml 中,加上
6. //<uses-permission id="android.permission.CALL_PHONE" />
传 送SMS/MMS
1. //调用短信程序
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. it.putExtra("sms_body", "The SMS text");
4. it.setType("vnd.android-dir/mms-sms");
5. startActivity(it);
1. //传送消息
2. Uri uri = Uri.parse("smsto://0800000123");
3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
4. it.putExtra("sms_body", "The SMS text");
5. startActivity(it);
1. //传送 MMS
2. Uri uri = Uri.parse("content://media/external/images/media/23");
3. Intent it = new Intent(Intent.ACTION_SEND);
4. it.putExtra("sms_body", "some text");
5. it.putExtra(Intent.EXTRA_STREAM, uri);
6. it.setType("image/png");
7. startActivity(it);
传 送 Email
1. Uri uri = Uri.parse("mailto:xxx@abc.com");
2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
3. startActivity(it);
1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
3. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
4. it.setType("text/plain");
5. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. Intent it=new Intent(Intent.ACTION_SEND);
2. String[] tos={"me@abc.com"};
3. String[] ccs={"you@abc.com"};
4. it.putExtra(Intent.EXTRA_EMAIL, tos);
5. it.putExtra(Intent.EXTRA_CC, ccs);
6. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
7. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
8. it.setType("message/rfc822");
9. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. //传送附件
2. Intent it = new Intent(Intent.ACTION_SEND);
3. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
4. it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
5. sendIntent.setType("audio/mp3");
6. startActivity(Intent.createChooser(it, "Choose Email Client"));
播 放多媒体
Uri uri = Uri.parse("file:///sdcard/song.mp3");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setType("audio/mp3");
startActivity(it);
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
Market 相关
1. //寻找某个应用
2. Uri uri = Uri.parse("market://search?q=pname:pkg_name");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where pkg_name is the full package path for an application
1. //显示某个应用的相关信息
2. Uri uri = Uri.parse("market://details?id=app_id");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where app_id is the application ID, find the ID
6. //by clicking on your application on Market home
7. //page, and notice the ID from the address bar
Uninstall 应用程序
1. Uri uri = Uri.fromParts("package", strPackageName, null);
2. Intent it = new Intent(Intent.ACTION_DELETE, uri);
3. startActivity(it);
===============================================================================
1 调用浏览器 载入某网址
view plaincopy to clipboardprint?
Uri uri = Uri.parse("http://www.baidu.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
2 Broadcast接收系统广播的intent 监控应用程序包的安装 删除
view plaincopy to clipboardprint?
public class getBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){
Toast.makeText(context, "有应用被添加", Toast.LENGTH_LONG).show();
}
elseif(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){
Toast.makeText(context, "有应用被删除", Toast.LENGTH_LONG).show();
}
elseif(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){
Toast.makeText(context, "有应用被替换", Toast.LENGTH_LONG).show();
}
elseif(Intent.ACTION_CAMERA_BUTTON.equals(intent.getAction())){
Toast.makeText(context, "按键", Toast.LENGTH_LONG).show();
}
}
}
需要声明的权限如下AndroidManifest.xml
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="zy.Broadcast"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Broadcast"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="getBroadcast" android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED"></action>
<!-- <action android:name="android.intent.action.PACKAGE_CHANGED"></action>-->
<action android:name="android.intent.action.PACKAGE_REMOVED"></action>
<action android:name="android.intent.action.PACKAGE_REPLACED"></action>
<!-- <action android:name="android.intent.action.PACKAGE_RESTARTED"></action>-->
<!--<action android:name="android.intent.action.PACKAGE_INSTALL"></action>-->
<action android:name="android.intent.action.CAMERA_BUTTON"></action>
<data android:scheme="package"></data>
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
3 使用Toast输出一个字符串
view plaincopy to clipboardprint?
public void DisplayToast(String str)
{
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
}
4 把一个字符串写进文件
view plaincopy to clipboardprint?
public void writefile(String str,String path )
{
File file;
FileOutputStream out;
try {
//创建文件
file = new File(path);
file.createNewFile();
//打开文件file的OutputStream
out = new FileOutputStream(file);
String infoToWrite = str;
//将字符串转换成byte数组写入文件
out.write(infoToWrite.getBytes());
//关闭文件file的OutputStream
out.close();
} catch (IOException e) {
//将出错信息打印到Logcat
DisplayToast(e.toString());
}
}
5 把文件内容读出到一个字符串
view plaincopy to clipboardprint?
public String getinfo(String path)
{
File file;
String str="";
FileInputStream in;
try{
//打开文件file的InputStream
file = new File(path);
in = new FileInputStream(file);
//将文件内容全部读入到byte数组
int length = (int)file.length();
byte[] temp = new byte[length];
in.read(temp, 0, length);
//将byte数组用UTF-8编码并存入display字符串中
str =EncodingUtils.getString(temp,TEXT_ENCODING);
//关闭文件file的InputStream
in.close();
}
catch (IOException e) {
DisplayToast(e.toString());
}
return str;
}
6 调用Android installer 安装和卸载程序
view plaincopy to clipboardprint?
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/WorldCupTimer.apk")), "application/vnd.android.package-archive");
startActivity(intent); //安装 程序
Uri packageURI = Uri.parse("package:zy.dnh");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);//正常卸载程序
7 结束某个进程
view plaincopy to clipboardprint?
activityManager.restartPackage(packageName);
8 设置默认来电铃声
view plaincopy to clipboardprint?
public void setMyRingtone()
{
File k = new File("/sdcard/Shall We Talk.mp3"); // 设置歌曲路径
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Shall We Talk");
values.put(MediaStore.MediaColumns.SIZE, 8474325);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
values.put(MediaStore.Audio.Media.DURATION, 230);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
;}
需要的权限
view plaincopy to clipboardprint?
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

更多相关文章

  1. Android(安卓)Android使用JSON与服务器交互
  2. 修改android版本号
  3. android 获取网络资源
  4. Android项目中如果json字符串中key-value顺序很重要,不要使用Andr
  5. Android中通过资源文件获取drawable的几种方法
  6. Android(安卓)TextView属性ellipsize多行失效的解决思路
  7. Android中图像变换Matrix的原理、代码验证和应用
  8. android之调用webservice 实现图片上传
  9. github开源Android资源整理(八)工具库

随机推荐

  1. Android(安卓)Test 基础知识
  2. android camera(四):camera 驱动 GT2005
  3. Android(安卓)自定义view(二) 如何实现自
  4. Android(安卓)Studio主要目录及文件简介
  5. Android(安卓)支持多屏幕机制
  6. android 当前apn的状态以及获取
  7. android中处理json最佳方法
  8. Android(安卓)如何判断CPU是32位还是64位
  9. 一个不错的启动菜单显示屏动画效果
  10. cocos2d-x编译到android平台后,增加返回键