美文网首页
广播接收者

广播接收者

作者: yanghanbin_it | 来源:发表于2017-06-08 14:59 被阅读0次

广播接收者

  • Android: 系统在运行过程中,会产生很多事件,那么某些事件产生时,比如:电量改变,收发短信,拨打电话,屏幕解锁等,开机,系统会发送广播,只要应用程序接收这条广播,就知道系统发生了相应的事件,从而执行相应的代码,使用广播接受者,就可以收听广播

创建广播接收者

1.定义java类继承BroadcastReceiver
2.在清单文件中定义receiver节点,定义name属性,指定广播接收者的全类名
3.在intent-filter节点中,指定action子节点的值,必须要跟要接收者的广播中action匹配,比如,要接收打电话的广播,那么action的值必须为

        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />

4.因为打电话的广播中所包含的action就是 android.intent.action.NEW_OUTGOING_CALL
5.即便广播接收者进程已经被关闭,当系统发出的广播中的action跟广播接收者的action匹配时,系统会重启改广播接收者进程

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void save(View v) {
        //保存IP号码
        EditText et = (EditText) findViewById(R.id.ip_et);
        SharedPreferences sp = getSharedPreferences("ip", MODE_PRIVATE);
        sp.edit().putString("ip", et.getText().toString()).commit();
    }
}
public class CallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 添加IP线路
        // 在打电话的广播中,会携带拨打的电话号码,通过以下号码获取到
        String phone = getResultData();
        SharedPreferences sp = context.getSharedPreferences("ip",
                Context.MODE_PRIVATE);
        String ip = sp.getString("ip", "");
        
        // 把iphone和ip号码重新拼装起来
        phone = ip + phone;
        
        //把新的号码重新放入广播中
        setResultData(phone);
    }
}  
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="com.example.ipphoen.CallReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
        </receiver>
    </application>  

相关文章

网友评论

      本文标题:广播接收者

      本文链接:https://www.haomeiwen.com/subject/skftqxtx.html