Android常用代码总结(一)

来源:互联网 发布:java法尔克 编辑:程序博客网 时间:2024/06/15 21:42

系统服务

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
}
}
};
1 0
原创粉丝点击