15个重要的Android代码

来源:互联网 发布:编程语言执行效率 编辑:程序博客网 时间:2024/04/30 05:54
<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;
// 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>
原创粉丝点击