华域联盟 Andriod Android自定义广播接收

Android自定义广播接收

本文实例为大家分享了Android自定义广播接收的具体代码,供大家参考,具体内容如下

实现效果:

MainActivity.java代码:

package com.henu.broadcastsample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void send(View v) {
        //动态注册广播接收
        receiver = new MyBroadcastReceiver();
        String action = "henurjxy";
        IntentFilter intentFilter=new IntentFilter(action);
        registerReceiver(receiver,intentFilter);
        Intent intend = new Intent("henurjxy");
        sendBroadcast(intend);
    }
//在页面销毁时,注销广播接收者
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

MyBroadcastReceiver.java代码:

package com.henu.broadcastsample;

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

public class MyBroadcastReceiver extends BroadcastReceiver {
public  MyBroadcastReceiver(){}
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"是我发出的广播哦",Toast.LENGTH_SHORT).show();
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » Android自定义广播接收

转载请保留出处和原文链接:https://www.cnhackhy.com/109353.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Android Studio+Servlet+MySql实现登录注册

Android实现仿iOS菊花加载圈动画效果

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们