Android 常驻广播和非常驻广播

移动开发 作者: 2024-08-25 04:00:01
一、知识准备 ①常驻广播接受者:使用AndroidManifest.xml注册,接受者不随Activity的销毁而销毁,也就是拥有独立的生命周期。 ②非常驻广播接受者:使用registerReceiv

一、知识准备

二、项目案例一

 1 import android.Manifest;
 2  android.content.BroadcastReceiver;
 3  android.content.IntentFilter;
 4  android.content.pm.PackageManager;
 5  android.support.v4.app.ActivityCompat;
 6  android.support.v4.content.ContextCompat;
 7  android.support.v7.app.AppCompatActivity;
 8  android.os.Bundle;
 9  android.util.Log;
10 
11  com.example.administrator.myapplication.receiver.NReceiver;
12 
13 public class MainActivity extends AppCompatActivity {
14 
15     BroadcastReceiver receiver = null;
16 
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_main);
21         getpermission();
22 
23         registerBroadcast();
24         
25     }
26 
27     private  getpermission() {
28         if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_SMS)
29                 != PackageManager.PERMISSION_GRANTED||ContextCompat.checkSelfPermission(MainActivity.30                 !=PackageManager.PERMISSION_GRANTED){
31             ActivityCompat.requestPermissions(MainActivity.this,new String[]{
32                     Manifest.permission.READ_SMS,Manifest.permission.RECEIVE_SMS
33             },1);
34         }
35 36 
37      registerBroadcast() {
38         receiver =  NReceiver();
39         IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED"40         registerReceiver(receiver,filter);
41         Log.i("TAG","registerBroadcast: ---------register"42 43 
44 45      onDestroy() {
46         .onDestroy();
47         unregisterReceiver(receiver);
48 49 }
1     <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
2     ="android.permission.RECEIVE_SMS">

 二、项目案例二

1 receiver
2             =".receiver.NReceiver"
3             android:enabled="true"
4             android:exported="true"5             intent-filter 6                 action ="android.provider.Telephony.SMS_RECEIVED"action7             </intent-filter8         receiver>
 2 
 3     BroadcastReceiver receiver =  4 
 6      7         13     14         15                 != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.16                 != PackageManager.PERMISSION_GRANTED) {
17             ActivityCompat.requestPermissions(MainActivity.18 19             },1)">23 }
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68190.html