天天看點

Android常用代碼總結(一) 系統服務正常 對話框GPS 媒體 藍牙

系統服務

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.CONNECTIVITY_SERVICE);           

6、輸入法管理器

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);           

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.NOTIFICATION_SERVICE);           

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);           

正常

1、發送短信

<uses-permission android:name="android.permission.SEND_SMS"/>              SmsManager sm = SmsManager.getDefault();              String destinationNumber ="0123456789";              String text = "Hello, MOTO!";              sm.sendTextMessage(destinationNumber, null, text, null, null);           

2、狀态欄通知

int notificationID = 10;              NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);              Notification notification = new Notification(R.drawable.yourIconId, "Put your notification text here", System.currentTimeMillis());              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);              notificationManager.notify(notificationID, notification);           

3、指定時間内手機震動

<uses-permission android:name="android.permission.VIBRATE"/>              Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);              vibrator.vibrate(1000);              vibrator.vibrate(new long[] {0, 200, 100, 100, 500, 500}, 4);           

對話框

1、日期選擇器對話框

DatePickerDialog.OnDateSetListener datePickerDialogListener = new DatePickerDialog.OnDateSetListener() {              public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {              //........              }              };              Calendar calendar = Calendar.getInstance();              int year = calendar.get(Calendar.YEAR);              int month = calendar.get(Calendar.MONTH);              int day = calendar.get(Calendar.DAY_OF_MONTH);              DatePickerDialog datePickerDialog = new DatePickerDialog(this,datePickerDialogListener,year, month, day);              datePickerDialog.show();           

2、時間選取器對話框

TimePickerDialog.OnTimeSetListener timePickerDialogListener = new TimePickerDialog.OnTimeSetListener() {              public void onTimeSet(TimePicker view, int hourOfDay, int minute) {              //.........              }              };              Calendar c = Calendar.getInstance();              int hour = c.get(Calendar.HOUR_OF_DAY);              int minute = c.get(Calendar.MINUTE);              TimePickerDialog timerPickerDialog = new TimePickerDialog(this,timePickerDialogListener, hour, minute, false);              timerPickerDialog.show();           

3、全屏顯示

int flag = WindowManager.layoutParams.FLAG_FULLSCREEN;//定義全屏參數              getWindow().setFlags(flag,flag);//設定flag标示           

GPS

1、擷取目前的GPS坐标

<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) {                  }              public void onStatusChanged(String provider, int status, Bundle extras) {                  }              public void onProviderDisabled(String provider) {                  }              public void onLocationChanged(Location location) {              double latitute = location.getLatitude();              double longitude = location.getLongitude();              }              });           

2、擷取最近一次已知的GPS坐标

<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();              });           

3、GPS坐标之間的距離

Location src = new Location("gps");              Location dest = new Location("gps");              src.setLatitude(originLatitude);              src.setLongitude(originLongitude);              dest.setLatitude(originLatitude);              dest.setLongitude(originLongitude);              float distance = src.distanceTo(dest);           

4、注冊監聽GPS狀态變化

<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;              }              }              });           

5、注冊監聽鄰近提示

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>              PendingIntent pendingIntent = getPendindIntent();              LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);              locationManager.addProximityAlert(latitude, longitude, radius, -1, pendingIntent);              public PendingIntent getPendindIntent() {              // return PendingIntent.getService(Context, int, Intent, int);              // return PendingIntent.getActivity(Context, int, Intent, int);              return PendingIntent.getBroadcast(Context, int, Intent, int);              }           

媒體

1、播放應用程式自帶的音頻或視訊檔案

MediaPlayer mp = MediaPlayer.create(this, R.raw.soundId);              mp.start();           

2、播放位于指定的檔案路徑或 URL 的音頻或視訊

MediaPlayer mp = new MediaPlayer();              mp.setDataSource(FILE_PATH_OR_URL);              mp.prepare();              mp.start();           

3、開始錄制音頻

<uses-permission android:name="android.permission.RECORD_AUDIO"/>              MediaRecorder recorder = new MediaRecorder();              recorder.setAudioSource(MediaRecorder.AudioSource.MIC);              recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);              recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);              recorder.setOutputFile(PATH_NAME); // The file must already exist              recorder.prepare();              recorder.start();           

4、停止錄制音頻

recorder.stop();              recorder.release();           

藍牙

1、驗證是否支援藍牙

<uses-permission android:name="android.permission.BLUETOOTH"/>              BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();              if (btAdapter == null) {              // Bluetooth is not supported, do something here to warn the user              return;              }           

2、連接配接至裝置

<uses-permission android:name="android.permission.BLUETOOTH"/>              UUID MY_UUID = UUID.fromString("yourdata");              BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();              BluetoothSocket socket = null;              try {              socket = device.createRfcommSocketToServiceRecord(MY_UUID);              btAdapter.cancelDiscovery();              socket.connect();              } catch(IOException e) {              //.........              } finally {              socket.close();              }           

3、啟用藍牙

<uses-permission android:name="android.permission.BLUETOOTH"/>              int ENABLE_BLUETOOTH = 1;              BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();              if (btAdapter == null) return;              if (!btAdapter.isEnabled()) {              Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);              startActivityForResult(enableBluetooth, ENABLE_BLUETOOTH);              // Now implement the onActivityResult() and wait for it to be invoked with ENABLE_BLUETOOTH              }           

4、擷取成對裝置

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();              Set<BluetoothDevice> devices = btAdapter.getBondedDevices();              if (devices.size() > 0) {              for (BluetoothDevice pairedDevice : devices) {              // do something useful with the device              }              }           

5、確定可檢測此裝置

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();              if (btAdapter == null) return;              if (btAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {              Intent makeDiscoverable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);              makeDiscoverable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);              // In a real situation you would probably use startActivityForResult to get the user decision.              startActivity(makeDiscoverable);              }           

6、等待傳入連接配接

UUID MY_UUID = UUID.fromString("yourdata");              String NAME = "BluetoothExample";              BluetoothServerSocket btServerSocket =  null;              BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();              BluetoothSocket socket = null;              try {              btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);              socket = btServerSocket.accept();              } catch (IOException e) {              // Deal with it              }              if (socket != null) {              InputStream inputStream = null;              OutputStream outputStream = null;              try {              inputStream = socket.getInputStream();              outputStream = socket.getOutputStream();              } catch (IOException e) {              // Deal with it              }              }           

7、遠端裝置檢測寄存器

IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);              this.registerReceiver(bluetoothReceiver, intentFilter);              intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);              this.registerReceiver(bluetoothReceiver, intentFilter);              private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {              @Override              public void onReceive(Context context, Intent intent) {              String action = intent.getAction();              if (BluetoothDevice.ACTION_FOUND.equals(action)) {              BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);              if (device.getBondState() != BluetoothDevice.BOND_BONDED) {              // device is not already paired. Do something useful here.              }              } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {              // do something useful here              }              }              };