Broadcast消息机制
广播-消息体-消息管理-消息接收
实例:
1.定义activity
package com.douzi.broacast;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BroacastActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Button button = new Button(BroacastActivity.this);
button.setText("点我发消息");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction("com.douzi.mybroacast");
sendOrderedBroadcast(intent, null);
//sendBroadcast(intent);
}
});
setContentView(button);
}
}
2.定义广播类
package com.douzi.broacast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyBroacastReveiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("com.douzi.mybroacast")){
Log.i("douzilog", "获得消息");
}
}
}
3.注册广播组件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.douzi.broacast"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".BroacastActivity"
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=".MyBroacastReveiver">
<intent-filter android:priority="1">
<action android:name="com.douzi.mybroacast"/>
</intent-filter>
</receiver>
<receiver android:name=".MyBroacastReveiver2">
<!-- android:priority数值大的优先 -->
<intent-filter android:priority="2">
<action android:name="com.douzi.mybroacast"/>
</intent-filter>
</receiver>
<receiver android:name=".SmsReveiver">
<intent-filter android:priority="3">
<action android:name="android.proivder.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
</manifest>