使用BroadcastReceiver步骤:
1)编写类继承BroadcastReceiver,复写onRecevier()方法。
2) 在AndroidManifest.xml文件中注册BroadcastReceiver
3)构建Intent对象
4)调用sengBroadcast()方法发送广播
1、编写类继承BroadcastReceiver,复写onRecevier()方法。
创建com.example.receiver包,构建MyReceiver类,复写onRecevier()方法,用于接收广播消息。
package com.example.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver{
private static final String brocast = "MyReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i(brocast, "onReceive");
}
}
2、
在AndroidManifest.xml文件中注册BroadcastReceiver
<activity android:name="com.example.receiver.MyReceiver">
<intent-filter >
<action android:name="com.example.receiver.ACTION"/>
</intent-filter>
</activity>
说明:
com.example.receiver.ACTION:广播类型。在系统启动时,就会注册一系列的广播。可自定义,也可使用系统广播类型。
3、发送广播:
构建Intent对象 并调用sengBroadcast()方法发送广播。
package com.example.test17;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
protected static final String action = "com.example.receiver.ACTION";
private Button myBroadcastBtn = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBroadcastBtn = (Button)findViewById(R.id.myBroadcastBtn);
myBroadcastBtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(action);
sendBroadcast(intent);
}
});
}
}
说明:
intent.setAction(action); 指定发送广播到action所指定的类型,action的类型值在AndroidManifest.xml文件中定义:
protected static final String action = "com.example.receiver.ACTION";
当查找到匹配的广播类型(com.example.receiver.ACTION),就是指定该类型所在包(com.example.receiver.MyReceiver)下的onReceive() 方法接收消息。