转载请说明出处
最近在做公司新产品的设计,想到广播效果设计加入到项目应该挺不错的,所以我们想将这个设计理念加入到我们的产品中。
电话状态实例
要先创建一个新Activity
package com.dzz.android20_phonest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; import android.util.Log; /** * Created by 朝花偏不夕拾 on 2017/2/7. */ public class MyPhoneState extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { if("android.intent.action.PHONE_STATE".equals(intent.getAction())){ //获取电话号码 String number=intent.getStringExtra("incoming_number"); Log.i("test","有电话进来了"+number); //获取电话状态 //电话管理者 TelephonyManager tm= (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); int state= tm.getCallState(); switch (state){ case TelephonyManager.CALL_STATE_RINGING://来电 Log.i("test","来电话了_前"); break; case TelephonyManager.CALL_STATE_OFFHOOK://接听 Log.i("test","通话中_中"); break; case TelephonyManager.CALL_STATE_IDLE: //挂断 Log.i("test","挂断了_后"); break; } } } }清单文件中配置 和加权限
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dzz.android20_phonest">
<!--读取电话状态权限--> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<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=".MyPhoneState"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE"></action> </intent-filter> </receiver>
</application> </manifest>
test: 结果
注:BroadcastReceiver 生命周期有 onReceive 一个