个人总结:
(1)跟Windows编程里面消息处理原理是一样的。
首先,需要注册消息处理函数,一旦受到该类消息,立即调用该函数进行响应
(2)不同与windows的地方,android消息接收函数放在BroadcastReciver继承类中。执行完onReceive函数后,kill对象。我估计可能考虑效率问题,占内存。每次需要响应消息时,重新生成该对象进行处理。
(3)有点疑问还没有明白,
<receiver android:name="com.example.testbroadcastreciver.TestReciever">
<intent-filter >
<action android:name="android.intent.action.EDIT"/>
</intent-filter>
</receiver>
为什么android:name="android:intent.action.EDIT" 按alt + "/"提示不来EDIT常量??实际上运行又没有啥问题。
(1)Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testbroadcastreciver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.testbroadcastreciver.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.testbroadcastreciver.TestReciever">
<intent-filter >
<action android:name="android.intent.action.EDIT"/>
</intent-filter>
</receiver>
</application>
</manifest>
(2)MainActivity //包含一个button, 里面调用sendBroadcast Message方法
package com.example.testbroadcastreciver;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button reciever = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reciever = (Button)findViewById(R.id.broadcastreciever);
reciever.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(Intent.ACTION_EDIT);
MainActivity.this.sendBroadcast(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
(3)TestReceiver.java //广播处理类
package com.example.testbroadcastreciver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TestReciever extends BroadcastReceiver {
public TestReciever() {
System.out.println("create a receiver");
}
/* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("Receive a broadcast message!");
}
}