字符串资源的定义
文件路径:res/values/strings.xml
字符串资源定义示例:
字符串资源的调用
在 Layout XML 调用字符串资源:
在 Activity 获取字符串资源:
从 Context 获取字符串资源:
从 Application 获取字符串资源:
[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.字符串资源
>>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 <b> %2d new messages </b></string> <!--同时包含占位符和html标签的字符串--> </resources>
由于需要使用Html.formHTML方法处理字符串,因此HTML标签中的 "<" 需要使用 "<" 表示 ">" 并不需要处理
获取字符串:
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>
传入的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:
// <uses-permission android:name="android.permission.GET_TASKS"/>
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:
// <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
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:
// <uses-permission android:name="android.permission.DEVICE_POWER"/>
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:
// <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
1.15 实例化Vibrator及权限配置
// AndroidManifest.xml must have the following permission:
// <uses-permission android:name="android.permission.VIBRATE"/>
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
1.16 实例化WallpaperService
// AndroidManifest.xml must have the following permission:
// <uses-permission android:name="android.permission.SET_WALLPAPER"/>
WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE);
1.17 实例化WifiManager
// AndroidManifest.xml must have the following permission:
// <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
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:
// <uses-permission android:name="android.permission.SEND_SMS"/>
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:
// <uses-permission android:name="android.permission.VIBRATE"/>
// Vibrate for 1000 miliseconds
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
2.5 间歇震动及权限配置
// AndroidManifest.xml must have the following permission:
//<uses-permission android:name="android.permission.VIBRATE"/>
// 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创建菜单
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_0"
android:title="Menu Item 0" />
<item android:id="@+id/menu_1"
android:title="Menu Item 1" />
</menu>
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:
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
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:
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
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:
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
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:
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// 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;
// latitude the latitude of the central point of the alert region
// longitude the longitude of the central point of the alert region
// radius the 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>