15個重要的Android代碼

<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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章