Android Studio中用adb shell发送广播调试应用

1.程序源码:

package com.runoob.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

public class MainActivity extends AppCompatActivity {

    private IntentFilter m_oIntentFilter;
    private MyBroadcastReceiver m_oMyBroadcastReceiver;
    private LocalBroadcastManager m_localBroadcastManager;

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

        findViewById(R.id.btn_send_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //发送广播
                Intent oIntent = new Intent();
                oIntent.setAction("com.runoob.myapplication.MY_BROADCAST");
                oIntent.putExtra("name", "this is myString");
                sendBroadcast(oIntent);

                //应用内通信
                /*Intent oIntent = new Intent();
                oIntent.setAction("com.runoob.myapplication.MY_BROADCAST");
                oIntent.putExtra("name", "this is myString");
                //m_localBroadcastManager.sendBroadcast(oIntent);*/
            }
        });
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        //动态注册接收器
        m_oIntentFilter        = new IntentFilter();
        m_oMyBroadcastReceiver = new MyBroadcastReceiver();

        m_oIntentFilter.addAction("com.runoob.myapplication.MY_BROADCAST");
        registerReceiver(m_oMyBroadcastReceiver, m_oIntentFilter);

        //应用内通信
       /*m_oMyBroadcastReceiver  = new MyBroadcastReceiver();
        m_oIntentFilter         = new IntentFilter();
        m_oIntentFilter.addAction("com.runoob.myapplication.MY_BROADCAST");

        m_localBroadcastManager = LocalBroadcastManager.getInstance(this);

        m_localBroadcastManager.registerReceiver(m_oMyBroadcastReceiver, m_oIntentFilter);*/

    }

    @Override
    protected void onPause(){
        super.onPause();

        unregisterReceiver(m_oMyBroadcastReceiver);
    }



    //接收广播
    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            if(action.equals("com.runoob.myapplication.MY_BROADCAST")) {
                String sReceivedString = intent.getStringExtra("string");
                Toast.makeText(context,"name="+sReceivedString,Toast.LENGTH_LONG).show();
            }

        }
    }


}

2. 执行adb shell命令:

发布了92 篇原创文章 · 获赞 23 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Tokyo_2024/article/details/100519045