Android从愚蒙到有知——NO.7

Android从无知到有知——NO.7

 

          前面做的ip拨号器在监听外拨电话时用的是系统提供的广播事件,而有些时候我们需要自己设定广播事件来满足特定的需要。Ok,今天整一下自定义广播事件,我们用一个状态监测模块向一个3G模块发送报警信息来实现这一想法。

         先定义一个3g模块用来接收特定的广播:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="俺是一个3g模块~~~~" />

          Android从愚蒙到有知——NO.7

        然后设置它的自定义广播事件:

<receiver android:name=".MyBro">
            <intent-filter>
                <action android:name="com.heng.lh"/>
            </intent-filter>
</receiver>

          这里的com.heng.lh是我们自己定义的广播事件,用来接收特定频道的信号。

             然后让我们“吐丝”一下,如果有自定义的广播发过来便给用户一个提示。

public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "检测到一个广播事件",1).show();
	}


         接收广播的模块做好了,然后就要设定发送广播的模块了,主界面需要一个按钮来向3G模块发送报警信息:

<Button
        android:onClick="click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="向3G模块发送信息" />

         我们来写一下这个点击事件,new出来一个意图,然后设定它的动作,也就是我们前面自定义的“com.heng.lh”,最后用sendBroadcast把信息发送出去。

public void click(View view){
		Intent intent=new Intent();
		intent.setAction("com.heng.lh");
		//把报警信息发送给3G模块
		sendBroadcast(intent);
	}

         这样3G模块便会收到一个广播信息,一个简单的自定义广播事件也就创建好了。

Android从愚蒙到有知——NO.7