BroadcastReceiver 案例

  BroadcastReceiver 可以接收来自系统和应用的广播,他的生命周期非常简单,只是从对象开始调用他到运行onReceiver方法之后就结束了。要想使用BroadcastReceiver和使用Activity一样首先要继承他。

1:activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText 
        android:id="@+id/et_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入广播消息"/>
    
    <Button 
        android:id="@+id/btn_send"
        android:layout_below="@id/et_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send"/>

</RelativeLayout>

2:MainActivity.java

public class MainActivity extends Activity {
    private EditText etInfo=null;
    private Button btnSend=null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        etInfo=(EditText)findViewById(R.id.et_info);
        btnSend=(Button)findViewById(R.id.btn_send);
        
        btnSend.setOnClickListener(new OnClickListener(){
            public void onClick(View view){
                String info=etInfo.getText().toString();
                Intent intent=new Intent();
                //setAction()中的字符串的值与AndroidManifest.xml中 receiver->action中的值相同
                intent.setAction("com.example.broadcast.MyBroadcastReceiverTest");
                intent.putExtra("info", info);
                sendBroadcast(intent);
            }
        });
    }
}

3:MyBroadcastReceiver.java

public class MyBroadcastReceiver  extends BroadcastReceiver{
    private Context context=null;
    
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        this.context=arg0;
        showNotification(arg1);
    }
    
    private void showNotification(Intent intent){
        String info=intent.getExtras().getString("info");
        
        NotificationManager nm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n=new Notification(R.drawable.ic_launcher,info,System.currentTimeMillis());
        PendingIntent pi=PendingIntent.getActivity(context, 0, new Intent(context,MainActivity.class), 0);
        
        n.setLatestEventInfo(context, info, null, pi);
        nm.notify(R.layout.activity_main,n);
    }
}

4:AndroidManifest.xml

 <receiver android:name="com.example.broadcast.MyBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.broadcast.MyBroadcastReceiverTest"/>
            </intent-filter>
        </receiver>

5:运行结果:

原文地址:https://www.cnblogs.com/yshyee/p/3374199.html