在线咨询
微信咨询
服务热线
服务热线:15639912513
TOP
当前位置:
首页 > 新闻中心> 安卓课堂>android无序广播发送与接收实例

android无序广播发送与接收实例

发布时间:2020-02-18 浏览:3578次

郑州app开发android无序广播发送与接收实例。思路如下,需要建立两个工程。其中一个是发送无序广播,另外一个是接收广播。

发送广播的java代码

package cn.xhhkj.cyd;

import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.text.TextUtils;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private Button btn;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btn=findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Intent intent=new Intent();

                intent.setAction("cn.xhhkj.broadcast");

                intent.putExtra("key","hello");

                sendBroadcast(intent);

            }

        });

    }

}

接收无序广播的java代码

package cn.xhhkj.xhhkjtest;


import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.util.Log;


public class Mybroadcast extends BroadcastReceiver {

    private static final String TAG = "MyReceiver";

    @Override

    public void onReceive(Context context, Intent intent) {

        Log.d(TAG,"接收到了"+intent.getStringExtra("key"));


    }

}

最后调试成功的代码

2020-02-18 13:04:38.669 2876-2876/cn.xhhkj.xhhkjtest D/MyReceiver: 接收到了hello


 


 


TAG
3578
该内容对我有帮助