广播里使用接口传数据

本文详细介绍了在Android中如何使用动态和静态广播,以及如何在广播接收器中通过接口回调更新UI。动态广播在Activity中注册并设置监听器,静态广播在AndroidManifest.xml中注册,并实现了数据变化时的回调通知机制。
摘要由CSDN通过智能技术生成

广播里使用接口传数据

一、动态广播;
二、静态广播。

一、动态广播中的使用:

1、新建一个接口类:
public interface UpdateUIListenner {
 
    /**
     * 更新UI
     */
    void UpdateUI();
}
2、广播接收器:
public class MyReceiver extends BroadcastReceiver {
 
    UpdateUIListenner updateUIListenner;
 
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch(action){
        case "com.android.intent.MyAction":
        	updateUIListenner.UpdateUI();
        	break;
		...
		}
 
    }
 
    /**
     * 监听广播接收器的接收到的数据
     * @param updateUIListenner
     */
    public void SetOnUpdateUIListenner(UpdateUIListenner updateUIListenner) {
        this.updateUIListenner = updateUIListenner;
 
    }

}
3、Activity中使用:
public class MainActivity extends AppCompatActivity {
    MyReceiver myReceiver;
    TextView tv1;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.btnSend);
        tv1 = (TextView) findViewById(R.id.tv);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送广播
                Intent intent = new Intent();               
                intent.setAction("com.android.intent.MyAction");
                sendBroadcast(intent);
                Log.e("+++++","发送广播");
 
            }
        });
        //注册广播  -----
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.android.intent.MyAction");
        registerReceiver(myReceiver, intentFilter);
        myReceiver.SetOnUpdateUIListenner(new UpdateUIListenner() {
            @Override
            public void UpdateUI() {
                tv1.setText("收到广播,更新数据");
            }
        });
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
}

二、静态广播:

在静态广播中使用接口回调,需注意可能引起内存泄漏

1、BroadcastReceiver 广播接收器:
public class SdCardStateReceiver extends BroadcastReceiver {
    private static final String TAG = "SdCardStateReceiver";
    private final Handler mHandler = new Handler();
    ISdCardStatesListener mSdCardStatesListener;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        android.util.Log.i(TAG, "onReceive: action ="+action);
        switch (action) {
            case Intent.ACTION_MEDIA_MOUNTED:
                if (intent.getData() != null) {
                    //获取挂载的U盘、sd卡路径
                    String path = intent.getData().getPath();
                    Log.i(TAG, "media onReceive: ACTION_MEDIA_MOUNTED path=" + path);
                    if(!path.startsWith("/storage/emulated")){
                        //TFCard
                        if(path.contains("-TF-")){
                            addMountPath(path);
                            updateUsbSDState();
                            
                        } else {
                            //usb
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    long totalSize = getTotalSize(intent.getData().getPath());
                                    Log.i(TAG, "media onReceive: ACTION_MEDIA_MOUNTED usb path=" + path + " totalSize ="+totalSize );
                                    if(totalSize>1610612736L){
                                     
                                        addMountPath(path);
                                        mHandler.post(() -> {
                                            updateUsbSDState();
                                            
                                        });
                                    }
                                }
                            }).start();
                        }
                    }
                }
                break;
            case Intent.ACTION_MEDIA_UNMOUNTED:
            case Intent.ACTION_MEDIA_EJECT:
                if (intent.getData() != null) {
                    String path = intent.getData().getPath();
                    Log.i(TAG, "media onReceive: ACTION_MEDIA_UNMOUNTED path=" + path);
                    removeMountPath(path);
                    
                    updateUsbSDState();
                }
                break;
        }
    }
    public long getTotalSize(String path) {
        try {
            StatFs statFs = new StatFs(path);
            statFs.restat(path);
            return statFs.getBlockSizeLong()*statFs.getBlockCountLong();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void setSdCardReceiverStatesListener(ISdCardStatesListener sdCardStatesListener) {
        this.mSdCardStatesListener = sdCardStatesListener;
    }

    public interface ISdCardStatesListener {

       void addMountPath(String path);
       void removeMountPath(String path);
       void updateUsbSDState();

    }
//保存在Map集合中
    protected static Map<String, ISdCardStatesListener> mMapNotifys = new HashMap<String, ISdCardStatesListener>();

    public static void registerNotify(String notifyKey, ISdCardStatesListener mStatesListener) {
        if (!mMapNotifys.containsKey(notifyKey)) {
            mMapNotifys.remove(notifyKey);
            mMapNotifys.put(notifyKey, mStatesListener);
        }
    }

    public static void removeNotify(String notifyKey) {
        if (mMapNotifys.containsKey(notifyKey)) {
            mMapNotifys.remove(notifyKey);
        }
    }


    public void addMountPath(String path) {
        Log.i(TAG,"addMountPath path ="+path);
        try {
            for (ISdCardStatesListener notify : mMapNotifys.values()) {
                notify.addMountPath(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void removeMountPath(String path) {
        Log.i(TAG,"removeMountPath path ="+path);
        try {
            for (ISdCardStatesListener notify : mMapNotifys.values()) {
                notify.removeMountPath(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void updateUsbSDState() {
        Log.i(TAG,"updateUsbSDState");
        try {
            for (ISdCardStatesListener notify : mMapNotifys.values()) {
                notify.updateUsbSDState();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、AndroidManifest.xml里注册广播:

	......
 	  <receiver android:name=".SdCardStateReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_MOUNTED" />
                <action android:name="android.intent.action.MEDIA_UNMOUNTED" />
                <action android:name="android.intent.action.MEDIA_EJECT" />
                <data android:scheme="file" />
            </intent-filter>
        </receiver>
     ......

3、Activity中使用:

public class MainActivity extends AppCompatActivity implements SdCardStateReceiver.ISdCardStatesListener{
    
    TextView tv1;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册监听接口
  		SdCardStateReceiver.registerNotify("MySdCard", this);
  		
        tv1 = (TextView) findViewById(R.id.tv);
        }
        ......
    @Override
    public void addMountPath(String path) {
    	tv1.setText("U盘加载");
      			......
    }
    @Override
    public void removeMountPath(String path) {
        Log.d(TAG, "removeMountPath: path ="+path);
      		tv1.setText("U盘移除");
          	......
        }
    }
    @Override
    public void updateUsbSDState() {
        Log.i(TAG, "updateUsbSDState: ");
        tv1.setText("更新数据及状态");
        ......
    }
		......
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值