代码块:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send(View view){
Intent intent=new Intent();
intent.setAction("org.frxm.day10_broadcast.MyCast1");
intent.putExtra("msg","明天开始放假啦");
sendBroadcast(intent);
}
}
public class MyReceiver1 extends BroadcastReceiver {
public MyReceiver1() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyReceiver1",intent.getStringExtra("msg"));
NotificationManager manager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
builder.setContentTitle("放假通知");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentText(intent.getStringExtra("msg"));
manager.notify(1,builder.build());
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="org.frxm.day10_broadcast.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送广播"
android:onClick="send"
/>
</RelativeLayout>
AndroidMainifest中所需要涉及的知识:
<receiver
android:name=".MyReceiver1"
android:enabled="true"
android:exported="true">
<intent-filter>
<!--给广播接受者起一个名字,为了分别哪些广播发送的内容-->
<action android:name="org.frxm.day10_broadcast.MyCast1"/>
</intent-filter>
</receiver>