亲宝软件园·资讯

展开

Android广播接收 Android自定义广播接收

Lssの老父亲 人气:0
想了解Android自定义广播接收的相关内容吗,Lssの老父亲在本文为您仔细讲解Android广播接收的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论