BroadcastReceiverの情報をActivityに転送する方法

5499 ワード

方法:BroadcastReceiverでインタフェースを定義し、ActivityでBroadcastReceiverのオブジェクトを定義し、動的登録を採用し、Activityでインタフェースのメソッドを定義し、BroadcastReceiverオブジェクトを通じてこのメソッドを呼び出します.具体的なコードは以下の通りです.
カスタムBroadcastReceiver:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
private Handle handle;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        String msg=intent.getStringExtra("msg");
        handle.handle(msg);// 

    }
    public interface Handle{        // 
        public void handle(String s);
    };

public void setHandle(Handle handle)
{
    this.handle=handle;
}
}    

  Activity:
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements MyBroadcastReceiver.Handle {

private Button broad=null;
private MyBroadcastReceiver receiver;// 
private ServiceConnection serviceConnection =new ServiceConnection() {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        broad=(Button)super.findViewById(R.id.broad);


        receiver=new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.EDIT");
        registerReceiver(receiver,intentFilter);// 

        receiver.setHandle(this);
}

  
    broad.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent it=new Intent();
            it.setAction("android.intent.action.EDIT");

            it.putExtra("msg"," ");
            MainActivity.this.sendBroadcast(it);
        }
    });
    }

    @Override
// 
    public void handle(String s) {
   
        Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
    }
    protected void onDestroy() {
                super.onDestroy();
                unregisterReceiver(receiver);     // 
            }
 }

なお、ここでは動的登録を用いる、静的登録はできないため、Android Mainifestを構成する必要はない.xmlファイル