例子:
接收类:
}
Mainfest.xml
public class BroadcastActivity extends Activity {
private SMSReceiver sms = null;
private String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sms = new SMSReceiver();
IntentFilter f = new IntentFilter();
f.addAction(SMS_ACTION);
BroadcastActivity.this.registerReceiver(sms, f);
}
});
}
}
接收类:
public class SMSReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive message!!");
}
}
Mainfest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cn"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".BroadcastActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.VIBRATE"/>
</manifest>