当前位置:   article > 正文

获取系统服务getSystemService()的使用

getsystemservice

getSystemService()Android的一个重要API,它允许开发者获取系统的各种服务。

1.WindowManager

(1)获取屏幕大小&&dp与px的转换

  1. WindowManager windowManager= (WindowManager) getSystemService(WINDOW_SERVICE);
  2. DisplayMetrics displayMetrics=new DisplayMetrics();
  3. windowManager.getDefaultDisplay().getMetrics(displayMetrics);
  4. int widthPixels=displayMetrics.widthPixels;
  5. int heightPixels=displayMetrics.heightPixels;
  6. //虚拟像素(dp)*屏幕密度(density)=实际像素(px)
  7. density=displayMetrics.density;

(2)添加悬浮窗

  1. WindowManager windowManager= (WindowManager) getSystemService(WINDOW_SERVICE);
  2. View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.testLayout,null,false);
  3. WindowManager.LayoutParams layoutParams=new WindowManager.LayoutParams();
  4. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  5. layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
  6. //用于设置悬浮窗类型,即覆盖于所有应用之上且不受限于当前Activity
  7. } else {
  8. layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
  9. }
  10. layoutParams.format = PixelFormat.RGBA_8888;
  11. layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
  12. WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//设置不可触碰(触碰后传递给下一次)|不获焦点(使周围空白处操作不受影响)
  13. layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
  14. layoutParams.screenOrientation= ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
  15. layoutParams.width=10;
  16. layoutParams.height=10;
  17. layoutParams.x=10;
  18. layoutParams.y=10;
  19. windowManager.addView(view,layoutParams);

2.AudioManager

(1)获取最大音量(各类型)

(2)设置音量(各类型)

(3)选择声音类型(即使用/设置哪个类型音量)

  1. AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
  2. int max=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
  3. audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,max,AudioManager.FLAG_PLAY_SOUND); //AudioManager.FLAG_PLAY_SOUND(第三个参数)是一个标志,它指示在调整音量时是否播放声音效果,当前为调整时播放声音。

3.NotificationManager

(1)发送通知

  1. //获取通知管理者
  2. NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. //创建通知
  4. Notification notification;
  5. //创建点击跳转
  6. //PendingIntent四个参数分别为 环境 请求码 执行的Intent 标志
  7. //标志建议使用PendingIntent.FLAG_IMMUTABLE创建不可变PendingIntent,只有在某些功能依赖于 PendingIntent 的可变性,才应使用PendingIntent.FLAG_MUTABLE
  8. Intent intent=new Intent(MainActivity.this,SecondActivity.class);
  9. PendingIntent pendingIntent=PendingIntent.getActivity(MainActivity.this,1,intent,PendingIntent.FLAG_IMMUTABLE);
  10. //通知渠道是在API26以上使用,需判断
  11. if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
  12. //创建通知渠道
  13. NotificationChannel notificationChannel=new NotificationChannel("ChannelID","ChannelName", NotificationManager.IMPORTANCE_HIGH);
  14. //向通知管理器中创建通知渠道
  15. notificationManager.createNotificationChannel(notificationChannel);
  16. //设置通知
  17. notification= new Notification.Builder(MainActivity.this)
  18. .setChannelId("ChannelID") //渠道ID 要与渠道对应
  19. .setAutoCancel(false) //设置点击后是否清除通知
  20. .setContentTitle("标题")
  21. .setContentText("你好")
  22. .setSmallIcon(R.drawable.icon) //状态栏中小图标
  23. .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon)) //下拉显示的大图标-从res中获取资源并生成位图
  24. .setWhen(System.currentTimeMillis()) //设置发送时间-当前时间
  25. .setContentIntent(pendingIntent) //设置等待Intent(点击通知后执行,可不写)
  26. .build();
  27. }else {
  28. //设置通知
  29. notification= new Notification.Builder(MainActivity.this)
  30. .setAutoCancel(false)
  31. .setContentTitle("标题")
  32. .setContentText("你好")
  33. .setSmallIcon(R.drawable.icon) //状态栏中小图标
  34. .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon)) //下拉显示的大图标-从res中获取资源并生成位图
  35. .setWhen(System.currentTimeMillis()) //设置发送时间-当前时间
  36. .setContentIntent(pendingIntent) //设置等待Intent(点击通知后执行,可不写)
  37. .build();
  38. }
  39. //发送通知;参数为 通知的ID、通知
  40. notificationManager.notify(1,notification);
  41. //根据通知ID删除通知
  42. notificationManager.cancel(1);
  43. //删除全部通知
  44. notificationManager.cancelAll();

4.Vibrator

(1) 振动器振动

  1. //获取系统服务-振动器
  2. Vibrator vibrator= (Vibrator) getSystemService(VIBRATOR_SERVICE);
  3. //判断是否有振动器
  4. if(vibrator.hasVibrator()){
  5. //振动(参数为振动毫秒数-long型)
  6. vibrator.vibrate(1000);
  7. //振动(参数为振动频率,循环次数;循环次数为-1时表示不循环)
  8. //振动频率为 静止->振动->静止->振动->... ...的毫秒数
  9. vibrator.vibrate(new long[]{0,2000,2000,4000},-1);
  10. }
  11. ... ...
  12. //关闭或停止振动器
  13. vibrator.cancel();

5.AlarmManager 闹钟管理者

(1) 定时执行PendingIntent(如发送广播),App关闭依然执行

  1. //创建Intent意图,用于发送广播
  2. Intent intent=new Intent().setAction("MyTestBroadcast");
  3. //根据Intent意图创建PendingIntent等待意图
  4. PendingIntent pendingIntent=PendingIntent.getBroadcast(MainActivity.this,2333,intent,PendingIntent.FLAG_IMMUTABLE);
  5. //获取执行时间
  6. //创建Calendar
  7. Calendar calendar=Calendar.getInstance();
  8. //将时间设置为当前时间
  9. calendar.setTimeInMillis(System.currentTimeMillis());
  10. //增加时间
  11. calendar.add(Calendar.MILLISECOND,7);
  12. //获取最终时间
  13. long time=calendar.getTimeInMillis();
  14. //创建Alarm闹钟
  15. AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
  16. //设置闹钟
  17. alarmManager.set(AlarmManager.RTC_WAKEUP,time,pendingIntent);

6.InputMethodManager输入法管理者

(1) 软键盘展开

  1. //方法1 使用InputMethodManager收起键盘
  2. //编辑视图获取焦点
  3. editText.requestFocus();
  4. //展开软键盘
  5. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  6. imm.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT);
  7. //在上述代码中,editText是你想要显示键盘的EditText控件的引用。showSoftInput方法的第一个参数是你想要显示键盘的View,第二个参数是一个标志,通常为InputMethodManager.SHOW_IMPLICIT,表示如果没有焦点,也会显示键盘。
  8. //展开键盘前需要让编辑器获取焦点,如果展开后再获取焦点,可能会获取焦点失败。
  9. //方法2 设置软键盘状态
  10. //编辑视图获取焦点
  11. editText.requestFocus();
  12. //展开软键盘
  13. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  14. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
  15. //在上述代码中,toggleSoftInput方法的第一个参数是InputMethodManager.SHOW_FORCED,表示强制显示键盘,第二个参数通常为0。
  16. //方法3 失去焦点自动收起
  17. //获取焦点时,通常会自动触发软键盘展开。
  18. editText.clearFocus();

(2) 软键盘收起

  1. //方法1 使用InputMethodManager收起键盘
  2. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  3. imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
  4. //在上面的代码中,editText是你的EditText控件的引用。hideSoftInputFromWindow方法接受两个参数:第一个参数是与输入法交互的窗口标记,通常是EditText的getWindowToken()方法提供的,第二个参数是一个标志,通常为0。
  5. //方法2 设置软键盘状态
  6. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  7. imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
  8. //上述代码中的toggleSoftInput方法会切换软键盘的状态。第一个参数指定了软键盘的显示状态,InputMethodManager.HIDE_IMPLICIT_ONLY表示只在当前焦点不是EditText时才隐藏软键盘。第二个参数同样是一个标志,通常为0。
  9. //方法3 失去焦点自动收起
  10. //失去焦点时,通常会自动触发软键盘收起。
  11. editText.clearFocus();

7.CameraManager

(1) 启动Camera2

Camera2的使用

(2) 打开、关闭手电筒

单纯的开启手电筒我们可以使用CameraManager的.setTorchMode()方法。

cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)获取该相机特征是否可获取闪光灯。

  1. CameraManager cameraManager= (CameraManager) getSystemService(CAMERA_SERVICE);
  2. String cameraIdList[]=cameraManager.getCameraIdList();
  3. String cameraId = null;
  4. for(int i=0;i<cameraIdList.length;i++){
  5. CameraCharacteristics cameraCharacteristics=cameraManager.getCameraCharacteristics(cameraIdList[i]);
  6. //可获取闪光灯&&朝向为后置
  7. if(cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)&&
  8. cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)==CameraCharacteristics.LENS_FACING_BACK){
  9. cameraId=cameraIdList[i];
  10. break;
  11. }
  12. }
  13. //打开手电筒
  14. cameraManager.setTorchMode(cameraId,true);
  15. //关闭手电筒
  16. cameraManager.setTorchMode(cameraId,false);

8. SensorManager 传感器管理者

(1) 操作传感器(注册传感器监听)

  1. //传感器管理者
  2. SensorManager sensorManager= (SensorManager) view.getContext().getSystemService(Context.SENSOR_SERVICE);
  3. //传感器
  4. Sensor sensor=sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
  5. if(sensor!=null){
  6. //传感器不为空
  7. sensorManager.registerListener(new SensorEventListener() {
  8. public void onSensorChanged(SensorEvent sensorEvent) {
  9. // 数值变化
  10. // 光强度发生变化时的处理逻辑
  11. float lightIntensity = sensorEvent.values[0];
  12. }
  13. public void onAccuracyChanged(Sensor sensor, int i) {
  14. // 传感器精度发生变化时的回调方法
  15. }
  16. }, sensor, SensorManager.SENSOR_DELAY_NORMAL);
  17. }

9. JobScheduler

获取JobScheduler调度JobInfo(启动JobSevice)

创建一个继承JobService类的子类,并实现其中的onStartJob()方法和onStopJob()方法。

onStartJob()方法中重写后台任务逻辑,该方法返回true表示作业在这里执行,返回false表示作业执行完毕。

onStopJob()方法中重写作业取消逻辑,该方法返回true表示希望作业被重新调度,返回false表示作业无需再次执行。

想中止任务,可使用JobFinished(JobParameters jp,boolean b)方法并在onStartJob()返回false,该方法第一个参数是当前作业的参数(用于告知系统哪个作业结束了),第二个参数是是否重新调度作业。

  1. public class MyJobService extends JobService {
  2. @Override
  3. public boolean onStartJob(JobParameters params) {
  4. // 在这里执行后台任务逻辑
  5. // 返回 true 表示作业在这里执行,返回 false 表示作业已经执行完毕
  6. return true;
  7. // 停止JobService可使用 jobFinished(params, false)并返回false
  8. // jobFinished(params, false);
  9. // return false;
  10. }
  11. @Override
  12. public boolean onStopJob(JobParameters params) {
  13. // 在这里处理作业被取消的逻辑
  14. // 返回 true 表示希望作业被重新调度
  15. return false;
  16. }
  17. }

请注意,一定要包含 android:permission="android.permission.BIND_JOB_SERVICE" 。 

  1. <application
  2. ... ... >
  3. ... ...
  4. <service android:name=".MyJobService"
  5. android:permission="android.permission.BIND_JOB_SERVICE"
  6. android:exported="false"/>
  7. </application>

(1) 准备JobInfo(作业信息)
使用JobInfo.Builder创建,可在其中设置网络条件、充电条件、作业执行周期(单位毫秒)、设备重启自动重新调度作业。

(2) 获取JobScheduler(作业调度)
使用getSystemService(JOB_SCHEDULER_SERVICE)获取JobSecheduler。

(3) JobScheduler调度JobInfo
使用schedule()方法调度JobInfo,启动JobService。

  1. JobInfo jobInfo = new JobInfo.Builder(JOB_ID, new ComponentName(this, MyJobService.class))
  2. .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // 设置网络条件
  3. .setRequiresCharging(true) // 设置充电条件
  4. .setPeriodic(15 * 60 * 1000) // 设置作业的周期性执行,单位是毫秒
  5. //.setPersisted(true) // 设备重启,作业重新调度
  6. .build();
  7. JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
  8. jobScheduler.schedule(jobInfo);

10.LocationManager定位管理器

(1) 获取定位状态

  1. //获取定位功能状态
  2. public static boolean getGPSState(Context context){
  3. //获取定位管理器
  4. LocationManager locationManager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
  5. return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  6. }

(2) 获取最佳定位提供者

(3) 设置定位变化监听器(及定位状态监听器)

  1. //获取权限
  2. int i=ActivityCompat.checkSelfPermission(MainActivity.this,"android.permission.ACCESS_FINE_LOCATION");
  3. if(i!= PackageManager.PERMISSION_GRANTED){
  4. //无权限,请求权限
  5. requestPermissions(new String[]{"android.permission.ACCESS_FINE_LOCATION"},1234);
  6. }
  7. //创建定位条件器
  8. Criteria criteria=new Criteria();
  9. //设置精度,Criteria.ACCURACY_FINE表示精确,Criteria.ACCURACY_COARSE表示粗略
  10. criteria.setAccuracy(Criteria.ACCURACY_FINE);
  11. //设置是否需要海拔信息
  12. criteria.setAltitudeRequired(true);
  13. //设置是否需要方位信息
  14. criteria.setBearingRequired(true);
  15. //设置是否允许运营商扣费
  16. criteria.setCostAllowed(true);
  17. //设置对电源的需求
  18. criteria.setPowerRequirement(Criteria.POWER_LOW);
  19. //获取定位管理者
  20. LocationManager locationManager= (LocationManager) getSystemService(LOCATION_SERVICE);
  21. //获取最佳定位提供者;第二个参数表示是否只取可用的内容提供者
  22. String locationProvider=locationManager.getBestProvider(criteria,true);
  23. //判断定位提供者是否有效
  24. if(locationProvider!=null){
  25. //设置定位监听器;第一个参数为定位提供者,第二个参数为最小更新时间,第三个参数为最小更新距离,第四个参数为定位监听器
  26. locationManager.requestLocationUpdates(locationProvider, 300, 0, new LocationListener() {
  27. //定位发生变化时触发
  28. public void onLocationChanged(@NonNull Location location) {
  29. //解析Location对象中的数据
  30. }
  31. //定位提供者不可用时触发
  32. public void onProviderDisabled(@NonNull String provider) {}
  33. //定位提供者可用时触发
  34. public void onProviderEnabled(@NonNull String provider) {}
  35. //状态变更时触发
  36. public void onStatusChanged(String provider, int status, Bundle extras) {}
  37. });
  38. //获取最后的位置
  39. Location location=locationManager.getLastKnownLocation(locationProvider);
  40. }
  41. else{
  42. //无有效定位提供者
  43. }

11.WiFiManager WiFi管理器

(1) 获取WiFi状态

(2) 设置WiFi状态

  1. //获取WiFi状态
  2. public static boolean getWiFiState(Context context){
  3. WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  4. return wifiManager.isWifiEnabled();
  5. }
  6. //设置WiFi状态
  7. public static void setWiFiState(Context context,boolean state){
  8. WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  9. wifiManager.setWifiEnabled(state);
  10. }

12.ConnectivityManager 移动数据连接管理器

(1) 获取移动数据连接状态(反射调用)

(2) 设置移动数据连接状态(反射调用)

  1. //获取移动数据连接开关的状态
  2. public static boolean getMobileDataState(Context context){
  3. //获取连接管理器
  4. ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  5. boolean isOpen=false;
  6. try {
  7. //该方法为隐藏方法,需要通过反射调用
  8. String methodName="getMobileDataEnable";
  9. Method method=connectivityManager.getClass().getMethod(methodName);
  10. isOpen= (boolean) method.invoke(connectivityManager);
  11. }catch (Exception e){
  12. e.printStackTrace();
  13. }
  14. return isOpen;
  15. }
  16. //设置移动数据连接开关的状态
  17. public static void setMobileDataState(Context context,boolean state){
  18. //获取连接管理器
  19. ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  20. try{
  21. //该方法为隐藏方法,需要通过反射调用
  22. String methodName="setMobileDataEnable";
  23. Method method=connectivityManager.getClass().getMethod(methodName);
  24. method.invoke(connectivityManager,state);
  25. }catch (Exception e){
  26. e.printStackTrace();
  27. }
  28. }

(3) 获取网络连接信息(是否有网络、网络状态、网络类型/子类型)

  1. //获取连接管理器
  2. ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
  3. //获取网络信息
  4. NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
  5. //判断是否有网络连接
  6. if(networkInfo==null){
  7. //无网络
  8. textView.setText("无网络");
  9. return;
  10. }
  11. //获取网络状态
  12. NetworkInfo.State networkState=networkInfo.getState();
  13. if(networkState!= NetworkInfo.State.CONNECTED){
  14. //未连接
  15. textView.setText("网络未连接");
  16. return;
  17. }
  18. //获取网络类型
  19. int networkType=networkInfo.getType();
  20. if(networkType==ConnectivityManager.TYPE_WIFI){
  21. //WiFi
  22. textView.setText("连接WiFi");
  23. }
  24. else if(networkType==ConnectivityManager.TYPE_MOBILE){
  25. //移动数据
  26. textView.setText("连接移动数据");
  27. //获取网络子类型
  28. int subtype=networkInfo.getSubtype();
  29. if(subtype==TelephonyManager.NETWORK_TYPE_LTE|subtype==TelephonyManager.NETWORK_TYPE_IWLAN){
  30. textView.setText("连接4G");
  31. }
  32. }else {
  33. //其他
  34. textView.setText("连接其他网络");
  35. }

13.ConsumerIrManager消费者红外管理器

(1) 判断是否有红外发射器

(2) 发射红外信号

  1. //获取消费者红外管理器
  2. ConsumerIrManager consumerIrManager= (ConsumerIrManager) getSystemService(CONSUMER_IR_SERVICE);
  3. //判断是否有红外发射器
  4. if(consumerIrManager.hasIrEmitter()){
  5. textView.setText("该设备有红外发射器");
  6. }
  7. else {
  8. textView.setText("该设备无红外发射器");
  9. }
  10. //准备发射信息
  11. int pattern[]={
  12. //开头两数字代表引导码
  13. 9000,4500,
  14. //下面两行表示用户码
  15. 560,560,560,1680,560,560,560,560,560,560,560,560,560,560,560,560,
  16. 560,560,560,1680,560,560,560,1680,560,560,560,1680,560,560,560,1680,
  17. //下面一行表示数据码
  18. 560,560,560,1680,560,560,560,560,560,560,560,1680,560,560,560,560,
  19. //下面一行表示数据反码
  20. 560,1680,560,560,560,1680,560,1680,560,1680,560,560,560,1680,560,1680,
  21. //末尾两个数字表示结束码
  22. 560,20000
  23. };
  24. //发射,普通家电红外频率一般为38kHz
  25. consumerIrManager.transmit(38000,pattern);

14.BluetoothManager蓝牙管理器

(1) 搜索蓝牙设备

  1. public class MainActivity extends AppCompatActivity {
  2. private BluetoothAdapter bluetoothAdapter=null;
  3. private Button button=null;
  4. @SuppressLint("MissingInflatedId")
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. //获取控件
  9. button=findViewById(R.id.button);
  10. //获取蓝牙适配器
  11. //Android4.3以上支持BLE技术(即蓝牙4.0版本及以上)
  12. if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR2){
  13. //如需要使用BLE特性,需使用蓝牙管理器获取蓝牙适配器
  14. BluetoothManager bluetoothManager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
  15. bluetoothAdapter=bluetoothManager.getAdapter();
  16. }
  17. else {
  18. bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
  19. }
  20. //判断是否拥有蓝牙功能
  21. if(bluetoothAdapter!=null){
  22. //该设备有蓝牙功能
  23. openBluetooth();
  24. //为按钮设置扫描监听器
  25. button.setOnClickListener(new View.OnClickListener() {
  26. @SuppressLint("MissingPermission")
  27. public void onClick(View view) {
  28. //蓝牙适配器未在搜索中
  29. if(!bluetoothAdapter.isDiscovering()){
  30. //开始蓝牙搜索
  31. bluetoothAdapter.startDiscovery();
  32. }
  33. //定时停止蓝牙搜索
  34. new Thread(new Runnable() {
  35. public void run() {
  36. try {
  37. Thread.sleep(5000);
  38. } catch (InterruptedException e) {
  39. throw new RuntimeException(e);
  40. }
  41. //蓝牙适配器搜索中
  42. if(bluetoothAdapter.isDiscovering()){
  43. //取消蓝牙搜索
  44. bluetoothAdapter.cancelDiscovery();
  45. }
  46. }
  47. }).start();
  48. }
  49. });
  50. }
  51. else {
  52. //该设备无蓝牙功能
  53. }
  54. }
  55. private int mRequestCode=123456;
  56. /**
  57. * 打开蓝牙
  58. */
  59. @SuppressLint("MissingPermission")
  60. private void openBluetooth(){
  61. //获取蓝牙状态
  62. int bluetoothState=bluetoothAdapter.getState();
  63. //蓝牙状态不为打开状态且不为正在打开状态
  64. if(bluetoothState!=BluetoothAdapter.STATE_ON&&bluetoothState!=BluetoothAdapter.STATE_TURNING_ON){
  65. //弹出是否允许扫描蓝牙界面
  66. Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  67. startActivityForResult(intent,mRequestCode);
  68. }
  69. }
  70. @SuppressLint("MissingPermission")
  71. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  72. super.onActivityResult(requestCode, resultCode, data);
  73. //由蓝牙弹出窗返回
  74. if(requestCode==mRequestCode){
  75. if(resultCode==RESULT_OK){
  76. //蓝牙开启
  77. }
  78. else if(resultCode==RESULT_CANCELED) {
  79. //不允许蓝牙开启
  80. //弹出是否允许扫描蓝牙界面
  81. Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  82. startActivityForResult(intent,mRequestCode);
  83. }
  84. }
  85. }
  86. private MyReceiver myReceiver=null;
  87. protected void onStart() {
  88. super.onStart();
  89. //创建过滤器
  90. IntentFilter intentFilter=new IntentFilter();
  91. //添加发现蓝牙设备活动
  92. intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
  93. //添加绑定状态改变活动
  94. intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  95. //创建广播接收者对象
  96. myReceiver=new MyReceiver();
  97. //注册广播接收者
  98. registerReceiver(myReceiver,intentFilter);
  99. }
  100. protected void onStop() {
  101. super.onStop();
  102. //注销广播接收者
  103. unregisterReceiver(myReceiver);
  104. }
  1. public class MyReceiver extends BroadcastReceiver {
  2. public void onReceive(Context context, Intent intent) {
  3. //获取活动
  4. String action=intent.getAction();
  5. //发现蓝牙设备
  6. if(action.equals(BluetoothDevice.ACTION_FOUND)){
  7. //获取蓝牙设备
  8. BluetoothDevice bluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  9. }
  10. //绑定蓝牙状态改变
  11. else if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
  12. //获取蓝牙设备
  13. BluetoothDevice bluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  14. //获取绑定状态
  15. int bondState=bluetoothDevice.getBondState();
  16. //判断绑定状态
  17. if(bondState==BluetoothDevice.BOND_BONDED){
  18. //已绑定
  19. }
  20. else if(bondState==BluetoothDevice.BOND_BONDING){
  21. //正在绑定
  22. }
  23. else if (bondState==BluetoothDevice.BOND_NONE) {
  24. //未绑定
  25. }
  26. }
  27. }
  28. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/588989
推荐阅读
相关标签
  

闽ICP备14008679号