package com.example.broadcast001;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//为哪个广播 注册什么样的过滤器????
MyReceiver myReceiver = new MyReceiver();//广播
IntentFilter intentFilter = new IntentFilter("ACTION");//过滤器
//IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
//intentFilter.addAction(action);
//intentFilter.addCategory(category);
//intentFilter.addDataType(type);
//注册广播的方法在ContextWrapper中,所以要在activity里注册
registerReceiver(myReceiver, intentFilter);
findViewById(R.id.button1).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//发广播就这样
Intent intent=new Intent("ACTION");
//IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
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.activity_main, menu);
return true;
}
}
////////////////////////////////////////////////////////////////////////////广播类
package com.example.broadcast001;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{
}
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Toast.makeText(context, action, Toast.LENGTH_LONG).show();
}
}
/////////////////////////////////////manifest.xml注册广播
<!--广播注册-->
<manifest>
<receiver android:name=".SmsBroadCastReceiver">
<intent-filter android:priority="2000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
<!-- 权限申请 -->
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>
两种注册类型的区别是:
1)第一种不是常驻型广播,也就是说广播跟随程序的生命周期(代码注册广播)。
2)第二种是常驻型,也就是说当应用程序关闭后,如果有信息广播来,程序也会被系统调用自动运行(manifest.xml中注册广播)。