赞
踩
Android系统中内置了很多广播,例如手机开机完成、电池电量不足时都会发送一条广播。
为了监听来自系统或者应用程序的广播事件,Android系统提供了BroadcastReceiver(广播接收者)组件。
<?xml version="1.0" encoding="utf-8"?>
<manifest ………. >
<application ……… >
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
</receiver>
</application>
</manifest>
package cn.itcast.interceptcall; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText et_ipnumber; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_ipnumber = (EditText) findViewById(R.id.et_ipnumber); // 创建SharedPreferences对象 sp = getSharedPreferences("config", MODE_PRIVATE); } public void click(View view) { // 获取用户输入的拦截号码 String number = et_ipnumber.getText().toString().trim(); //创建Editor对象,保存用户输入的拦截号码 SharedPreferences.Editor editor = sp.edit(); editor.putString("number", number); editor.commit(); Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show(); } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.itcast.interceptcall" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".OutCallReceiver" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.intent.action.NEW_OUTGOING_CALL"/> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/> </manifest>
Android系统提供了两种广播类型,有序广播和无序广播,开发者可根据需求为程序设置不同的广播类型。
本章详细地讲解了广播接收者的相关知识,首先介绍了什么是广播接收者,然后讲解了如何自定义广播以及广播的类型。通过本章的学习,要求初学者能够熟练掌握广播接收者的使用,并在实际开发中进行应用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。