赞
踩
getSystemService()是Android的一个重要API,它允许开发者获取系统的各种服务。
- WindowManager windowManager= (WindowManager) getSystemService(WINDOW_SERVICE);
-
- DisplayMetrics displayMetrics=new DisplayMetrics();
-
- windowManager.getDefaultDisplay().getMetrics(displayMetrics);
-
- int widthPixels=displayMetrics.widthPixels;
- int heightPixels=displayMetrics.heightPixels;
-
- //虚拟像素(dp)*屏幕密度(density)=实际像素(px)
- density=displayMetrics.density;
- WindowManager windowManager= (WindowManager) getSystemService(WINDOW_SERVICE);
-
- View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.testLayout,null,false);
-
- WindowManager.LayoutParams layoutParams=new WindowManager.LayoutParams();
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
- //用于设置悬浮窗类型,即覆盖于所有应用之上且不受限于当前Activity
- } else {
- layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
- }
- layoutParams.format = PixelFormat.RGBA_8888;
-
- layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
- WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//设置不可触碰(触碰后传递给下一次)|不获焦点(使周围空白处操作不受影响)
-
- layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
- layoutParams.screenOrientation= ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
- layoutParams.width=10;
- layoutParams.height=10;
- layoutParams.x=10;
- layoutParams.y=10;
-
- windowManager.addView(view,layoutParams);

- AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
- int max=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
- audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,max,AudioManager.FLAG_PLAY_SOUND); //AudioManager.FLAG_PLAY_SOUND(第三个参数)是一个标志,它指示在调整音量时是否播放声音效果,当前为调整时播放声音。
- //获取通知管理者
- NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
-
- //创建通知
- Notification notification;
-
- //创建点击跳转
- //PendingIntent四个参数分别为 环境 请求码 执行的Intent 标志
- //标志建议使用PendingIntent.FLAG_IMMUTABLE创建不可变PendingIntent,只有在某些功能依赖于 PendingIntent 的可变性,才应使用PendingIntent.FLAG_MUTABLE
- Intent intent=new Intent(MainActivity.this,SecondActivity.class);
- PendingIntent pendingIntent=PendingIntent.getActivity(MainActivity.this,1,intent,PendingIntent.FLAG_IMMUTABLE);
-
- //通知渠道是在API26以上使用,需判断
- if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
-
- //创建通知渠道
- NotificationChannel notificationChannel=new NotificationChannel("ChannelID","ChannelName", NotificationManager.IMPORTANCE_HIGH);
- //向通知管理器中创建通知渠道
- notificationManager.createNotificationChannel(notificationChannel);
-
- //设置通知
- notification= new Notification.Builder(MainActivity.this)
- .setChannelId("ChannelID") //渠道ID 要与渠道对应
- .setAutoCancel(false) //设置点击后是否清除通知
- .setContentTitle("标题")
- .setContentText("你好")
- .setSmallIcon(R.drawable.icon) //状态栏中小图标
-
- .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon)) //下拉显示的大图标-从res中获取资源并生成位图
- .setWhen(System.currentTimeMillis()) //设置发送时间-当前时间
- .setContentIntent(pendingIntent) //设置等待Intent(点击通知后执行,可不写)
- .build();
-
- }else {
-
- //设置通知
- notification= new Notification.Builder(MainActivity.this)
- .setAutoCancel(false)
- .setContentTitle("标题")
- .setContentText("你好")
- .setSmallIcon(R.drawable.icon) //状态栏中小图标
-
- .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon)) //下拉显示的大图标-从res中获取资源并生成位图
- .setWhen(System.currentTimeMillis()) //设置发送时间-当前时间
- .setContentIntent(pendingIntent) //设置等待Intent(点击通知后执行,可不写)
- .build();
-
- }
-
- //发送通知;参数为 通知的ID、通知
- notificationManager.notify(1,notification);
-
- //根据通知ID删除通知
- notificationManager.cancel(1);
- //删除全部通知
- notificationManager.cancelAll();

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

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

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

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

单纯的开启手电筒我们可以使用CameraManager的.setTorchMode()方法。
cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)获取该相机特征是否可获取闪光灯。
- CameraManager cameraManager= (CameraManager) getSystemService(CAMERA_SERVICE);
- String cameraIdList[]=cameraManager.getCameraIdList();
- String cameraId = null;
- for(int i=0;i<cameraIdList.length;i++){
- CameraCharacteristics cameraCharacteristics=cameraManager.getCameraCharacteristics(cameraIdList[i]);
- //可获取闪光灯&&朝向为后置
- if(cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)&&
- cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)==CameraCharacteristics.LENS_FACING_BACK){
- cameraId=cameraIdList[i];
- break;
- }
- }
- //打开手电筒
- cameraManager.setTorchMode(cameraId,true);
- //关闭手电筒
- cameraManager.setTorchMode(cameraId,false);

(1) 操作传感器(注册传感器监听)
- //传感器管理者
- SensorManager sensorManager= (SensorManager) view.getContext().getSystemService(Context.SENSOR_SERVICE);
- //传感器
- Sensor sensor=sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
- if(sensor!=null){
- //传感器不为空
- sensorManager.registerListener(new SensorEventListener() {
- public void onSensorChanged(SensorEvent sensorEvent) {
- // 数值变化
- // 光强度发生变化时的处理逻辑
- float lightIntensity = sensorEvent.values[0];
- }
- public void onAccuracyChanged(Sensor sensor, int i) {
- // 传感器精度发生变化时的回调方法
- }
- }, sensor, SensorManager.SENSOR_DELAY_NORMAL);
- }

获取JobScheduler调度JobInfo(启动JobSevice)
创建一个继承JobService类的子类,并实现其中的onStartJob()方法和onStopJob()方法。
onStartJob()方法中重写后台任务逻辑,该方法返回true表示作业在这里执行,返回false表示作业执行完毕。
onStopJob()方法中重写作业取消逻辑,该方法返回true表示希望作业被重新调度,返回false表示作业无需再次执行。
想中止任务,可使用JobFinished(JobParameters jp,boolean b)方法并在onStartJob()返回false,该方法第一个参数是当前作业的参数(用于告知系统哪个作业结束了),第二个参数是是否重新调度作业。
- public class MyJobService extends JobService {
- @Override
- public boolean onStartJob(JobParameters params) {
- // 在这里执行后台任务逻辑
-
- // 返回 true 表示作业在这里执行,返回 false 表示作业已经执行完毕
- return true;
-
- // 停止JobService可使用 jobFinished(params, false)并返回false
- // jobFinished(params, false);
- // return false;
- }
-
- @Override
- public boolean onStopJob(JobParameters params) {
- // 在这里处理作业被取消的逻辑
-
- // 返回 true 表示希望作业被重新调度
- return false;
- }
- }

请注意,一定要包含 android:permission="android.permission.BIND_JOB_SERVICE" 。
- <application
- ... ... >
- ... ...
-
- <service android:name=".MyJobService"
- android:permission="android.permission.BIND_JOB_SERVICE"
- android:exported="false"/>
-
- </application>
(1) 准备JobInfo(作业信息)
使用JobInfo.Builder创建,可在其中设置网络条件、充电条件、作业执行周期(单位毫秒)、设备重启自动重新调度作业。
(2) 获取JobScheduler(作业调度)
使用getSystemService(JOB_SCHEDULER_SERVICE)获取JobSecheduler。
(3) JobScheduler调度JobInfo
使用schedule()方法调度JobInfo,启动JobService。
- JobInfo jobInfo = new JobInfo.Builder(JOB_ID, new ComponentName(this, MyJobService.class))
- .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // 设置网络条件
- .setRequiresCharging(true) // 设置充电条件
- .setPeriodic(15 * 60 * 1000) // 设置作业的周期性执行,单位是毫秒
- //.setPersisted(true) // 设备重启,作业重新调度
- .build();
-
- JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
- jobScheduler.schedule(jobInfo);
- //获取定位功能状态
- public static boolean getGPSState(Context context){
- //获取定位管理器
- LocationManager locationManager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
- return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- }
- //获取权限
- int i=ActivityCompat.checkSelfPermission(MainActivity.this,"android.permission.ACCESS_FINE_LOCATION");
- if(i!= PackageManager.PERMISSION_GRANTED){
- //无权限,请求权限
- requestPermissions(new String[]{"android.permission.ACCESS_FINE_LOCATION"},1234);
- }
-
- //创建定位条件器
- Criteria criteria=new Criteria();
- //设置精度,Criteria.ACCURACY_FINE表示精确,Criteria.ACCURACY_COARSE表示粗略
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- //设置是否需要海拔信息
- criteria.setAltitudeRequired(true);
- //设置是否需要方位信息
- criteria.setBearingRequired(true);
- //设置是否允许运营商扣费
- criteria.setCostAllowed(true);
- //设置对电源的需求
- criteria.setPowerRequirement(Criteria.POWER_LOW);
-
- //获取定位管理者
- LocationManager locationManager= (LocationManager) getSystemService(LOCATION_SERVICE);
- //获取最佳定位提供者;第二个参数表示是否只取可用的内容提供者
- String locationProvider=locationManager.getBestProvider(criteria,true);
-
- //判断定位提供者是否有效
- if(locationProvider!=null){
-
- //设置定位监听器;第一个参数为定位提供者,第二个参数为最小更新时间,第三个参数为最小更新距离,第四个参数为定位监听器
- locationManager.requestLocationUpdates(locationProvider, 300, 0, new LocationListener() {
- //定位发生变化时触发
- public void onLocationChanged(@NonNull Location location) {
- //解析Location对象中的数据
- }
-
- //定位提供者不可用时触发
- public void onProviderDisabled(@NonNull String provider) {}
-
- //定位提供者可用时触发
- public void onProviderEnabled(@NonNull String provider) {}
-
- //状态变更时触发
- public void onStatusChanged(String provider, int status, Bundle extras) {}
- });
-
- //获取最后的位置
- Location location=locationManager.getLastKnownLocation(locationProvider);
-
- }
- else{
- //无有效定位提供者
- }

- //获取WiFi状态
- public static boolean getWiFiState(Context context){
- WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
- return wifiManager.isWifiEnabled();
- }
-
- //设置WiFi状态
- public static void setWiFiState(Context context,boolean state){
- WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
- wifiManager.setWifiEnabled(state);
- }
- //获取移动数据连接开关的状态
- public static boolean getMobileDataState(Context context){
- //获取连接管理器
- ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- boolean isOpen=false;
- try {
- //该方法为隐藏方法,需要通过反射调用
- String methodName="getMobileDataEnable";
- Method method=connectivityManager.getClass().getMethod(methodName);
- isOpen= (boolean) method.invoke(connectivityManager);
- }catch (Exception e){
- e.printStackTrace();
- }
- return isOpen;
- }
-
- //设置移动数据连接开关的状态
- public static void setMobileDataState(Context context,boolean state){
- //获取连接管理器
- ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- try{
- //该方法为隐藏方法,需要通过反射调用
- String methodName="setMobileDataEnable";
- Method method=connectivityManager.getClass().getMethod(methodName);
- method.invoke(connectivityManager,state);
- }catch (Exception e){
- e.printStackTrace();
- }
- }

- //获取连接管理器
- ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
-
- //获取网络信息
- NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
- //判断是否有网络连接
- if(networkInfo==null){
- //无网络
- textView.setText("无网络");
- return;
- }
-
- //获取网络状态
- NetworkInfo.State networkState=networkInfo.getState();
- if(networkState!= NetworkInfo.State.CONNECTED){
- //未连接
- textView.setText("网络未连接");
- return;
- }
-
- //获取网络类型
- int networkType=networkInfo.getType();
- if(networkType==ConnectivityManager.TYPE_WIFI){
- //WiFi
- textView.setText("连接WiFi");
- }
- else if(networkType==ConnectivityManager.TYPE_MOBILE){
- //移动数据
- textView.setText("连接移动数据");
- //获取网络子类型
- int subtype=networkInfo.getSubtype();
- if(subtype==TelephonyManager.NETWORK_TYPE_LTE|subtype==TelephonyManager.NETWORK_TYPE_IWLAN){
- textView.setText("连接4G");
- }
- }else {
- //其他
- textView.setText("连接其他网络");
- }

- //获取消费者红外管理器
- ConsumerIrManager consumerIrManager= (ConsumerIrManager) getSystemService(CONSUMER_IR_SERVICE);
- //判断是否有红外发射器
- if(consumerIrManager.hasIrEmitter()){
- textView.setText("该设备有红外发射器");
- }
- else {
- textView.setText("该设备无红外发射器");
- }
- //准备发射信息
- int pattern[]={
- //开头两数字代表引导码
- 9000,4500,
- //下面两行表示用户码
- 560,560,560,1680,560,560,560,560,560,560,560,560,560,560,560,560,
- 560,560,560,1680,560,560,560,1680,560,560,560,1680,560,560,560,1680,
- //下面一行表示数据码
- 560,560,560,1680,560,560,560,560,560,560,560,1680,560,560,560,560,
- //下面一行表示数据反码
- 560,1680,560,560,560,1680,560,1680,560,1680,560,560,560,1680,560,1680,
- //末尾两个数字表示结束码
- 560,20000
- };
- //发射,普通家电红外频率一般为38kHz
- consumerIrManager.transmit(38000,pattern);

- public class MainActivity extends AppCompatActivity {
- private BluetoothAdapter bluetoothAdapter=null;
- private Button button=null;
- @SuppressLint("MissingInflatedId")
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //获取控件
- button=findViewById(R.id.button);
-
- //获取蓝牙适配器
- //Android4.3以上支持BLE技术(即蓝牙4.0版本及以上)
- if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR2){
- //如需要使用BLE特性,需使用蓝牙管理器获取蓝牙适配器
- BluetoothManager bluetoothManager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
- bluetoothAdapter=bluetoothManager.getAdapter();
- }
- else {
- bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
- }
-
- //判断是否拥有蓝牙功能
- if(bluetoothAdapter!=null){
- //该设备有蓝牙功能
- openBluetooth();
- //为按钮设置扫描监听器
- button.setOnClickListener(new View.OnClickListener() {
- @SuppressLint("MissingPermission")
- public void onClick(View view) {
- //蓝牙适配器未在搜索中
- if(!bluetoothAdapter.isDiscovering()){
- //开始蓝牙搜索
- bluetoothAdapter.startDiscovery();
- }
- //定时停止蓝牙搜索
- new Thread(new Runnable() {
- public void run() {
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- //蓝牙适配器搜索中
- if(bluetoothAdapter.isDiscovering()){
- //取消蓝牙搜索
- bluetoothAdapter.cancelDiscovery();
- }
- }
- }).start();
- }
- });
- }
- else {
- //该设备无蓝牙功能
- }
-
- }
-
- private int mRequestCode=123456;
- /**
- * 打开蓝牙
- */
- @SuppressLint("MissingPermission")
- private void openBluetooth(){
- //获取蓝牙状态
- int bluetoothState=bluetoothAdapter.getState();
- //蓝牙状态不为打开状态且不为正在打开状态
- if(bluetoothState!=BluetoothAdapter.STATE_ON&&bluetoothState!=BluetoothAdapter.STATE_TURNING_ON){
- //弹出是否允许扫描蓝牙界面
- Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- startActivityForResult(intent,mRequestCode);
- }
- }
-
- @SuppressLint("MissingPermission")
- protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- //由蓝牙弹出窗返回
- if(requestCode==mRequestCode){
- if(resultCode==RESULT_OK){
- //蓝牙开启
- }
- else if(resultCode==RESULT_CANCELED) {
- //不允许蓝牙开启
- //弹出是否允许扫描蓝牙界面
- Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- startActivityForResult(intent,mRequestCode);
- }
- }
- }
-
- private MyReceiver myReceiver=null;
- protected void onStart() {
- super.onStart();
- //创建过滤器
- IntentFilter intentFilter=new IntentFilter();
- //添加发现蓝牙设备活动
- intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
- //添加绑定状态改变活动
- intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
- //创建广播接收者对象
- myReceiver=new MyReceiver();
- //注册广播接收者
- registerReceiver(myReceiver,intentFilter);
- }
-
- protected void onStop() {
- super.onStop();
- //注销广播接收者
- unregisterReceiver(myReceiver);
- }

- public class MyReceiver extends BroadcastReceiver {
- public void onReceive(Context context, Intent intent) {
- //获取活动
- String action=intent.getAction();
- //发现蓝牙设备
- if(action.equals(BluetoothDevice.ACTION_FOUND)){
- //获取蓝牙设备
- BluetoothDevice bluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- }
- //绑定蓝牙状态改变
- else if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
- //获取蓝牙设备
- BluetoothDevice bluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- //获取绑定状态
- int bondState=bluetoothDevice.getBondState();
- //判断绑定状态
- if(bondState==BluetoothDevice.BOND_BONDED){
- //已绑定
- }
- else if(bondState==BluetoothDevice.BOND_BONDING){
- //正在绑定
- }
- else if (bondState==BluetoothDevice.BOND_NONE) {
- //未绑定
- }
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。