<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 实例化AlarmManagerAlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);1.3 实例化AudioManagerAudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);1.4 实例化ClipboardManagerClipboardManager 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 实例化InputMethodManagerInputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);1.7 实例化KeyguardManagerKeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);1.8 实例化LayoutInflaterLayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);1.9 实例化LocationManagerLocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);1.10 实例化NotificationManagerNotificationManager 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 实例化SearchManagerSearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);1.13 实例化SensorManagerSensorManager 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 实例化WindowManagerWindowManager 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 显示一个ToastToast.makeText(this, "Put your message here", Toast.LENGTH_SHORT).show();2.3 显示一个通知int notificationID = 10;NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// Create the notificationNotification 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 activityIntent 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 notificationnotificationManager.notify(notificationID, notification);2.4 使手机震动及权限配置// AndroidManifest.xml must have the following permission:// <uses-permission android:name="android.permission.VIBRATE"/>// Vibrate for 1000 milisecondsVibrator 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 emptyContentValues 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 herebreak;case MENU_ITEM_1:// put your code herebreak; 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 displayedDatePickerDialog.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 dateCalendar 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 DialogDatePickerDialog datePickerDialog = new DatePickerDialog(this,datePickerDialogListener,year, month, day);// Display Date Picker DialogdatePickerDialog.show();5.4 时间选择对话框// Define the date picker dialog listener, which will be called after// the user picks a time in the dialog displayedTimePickerDialog.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 timeCalendar c = Calendar.getInstance();int hour = c.get(Calendar.HOUR_OF_DAY);int minute = c.get(Calendar.MINUTE);// Create Time Picker DialogTimePickerDialog timerPickerDialog = new TimePickerDialog(this,timePickerDialogListener, hour, minute, false);// Display Time Picker DialogtimerPickerDialog.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 startedcase GpsStatus.GPS_EVENT_STARTED:// put your code herebreak;// Event sent when the GPS system has stoppedcase GpsStatus.GPS_EVENT_STOPPED:// put your code herebreak;// Event sent when the GPS system has received its first fix since startingcase GpsStatus.GPS_EVENT_FIRST_FIX:// put your code herebreak;// Event sent periodically to report GPS satellite statuscase GpsStatus.GPS_EVENT_SATELLITE_STATUS:// put your code herebreak;}}});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 metersLocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);locationManager.addProximityAlert(latitude, longitude, radius, -1, pendingIntent);7.6 未完待续...</pre>