android broadcast receiver sample (2015.12.3)

http://www.tutorialspoint.com/android/android_broadcast_receivers.htm


1. 在ManActivity.java中定义一个button响应API: 

这个API里面broadcast Intent出去。

    // broadcast a custom intent
    public void broadcastIntent(View view) {
    	Intent intent = new Intent();
    	intent.setAction("com.example.CUSTOM_INTENT");
    	sendBroadcast(intent);
    }


2. 新建一个java文件:MyReceiver.java:

package com.example.helloworld;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast; //  Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。而且Toast主要用于向用户显示提示消息


public class MyReceiver extends BroadcastReceiver {
<span style="white-space:pre">	</span>@Override
<span style="white-space:pre">	</span>public void onReceive(Context context, Intent intent) {
<span style="white-space:pre">		</span>Toast.makeText(context, "Intent Detected", Toast.LENGTH_LONG).show();
<span style="white-space:pre">	</span>}
}

3. 把新的receiver注册到Manifest.xml中:

       <receiver android:name="MyReceiver">
       
       <intent-filter>
          <action android:name="com.example.CUSTOM_INTENT">
          </action>
       </intent-filter>
       
       </receiver>


4. 修改界面xml, 增加一个button: 

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/stopServiceButton"
        android:layout_below="@+id/stopServiceButton"
        android:layout_marginTop="29dp"
        android:text="@string/broadcast_intent" 
        android:onClick="broadcastIntent"/>

这个button的OnClick回调函数,就应用第一步预先定义好的API.



Android Broadcast Intent

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值