发送自定义广播 For Android(自己发送自己接受)

1.新建一个项目,在activiy_main.xml中新建一个按钮,我们用来发送广播
activiy_main.xml↓↓↓




    

2.点击查看图片建立接收者的方法![J%V%BBR9V6R0Y(J$N~Z)OR.png
建立一个接受者 broader cast receiver ,名字随你定,这里我叫AnotherRecieviercastReciver,里面放置一个Toast就可以,让其显示信息我接收到了

package mylistview.lmq.cn.broadcasttest2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AnotherReceivercastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        Toast.makeText(context,"recived in anotherBroadcastReceiver",Toast.LENGTH_SHORT).show();
    }
}

3.我们要配置AndroidMainifest.xml,我们在建立broadcastReceiver之后,系统自己给我门在这里面注册了




    
        
            
                

                
            
        

        
            //这一句是我们加的
                
           //我们接受的广播是com.example.broadcasttest.MY_BROADCAST这一种的广播
            

        
    


4.我们来写MainActivity
将button加上监听,点击就会发送com.example.broadcasttest.MY_BROADCAST这一种的广播

package mylistview.lmq.cn.broadcasttest2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity01 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main01);
        Button button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });
    }
}

你可能感兴趣的:(发送自定义广播 For Android(自己发送自己接受))