如何使用 adb 在 Android 11 上触发 BroadcastReceiver? [英] How can I trigger a BroadcastReceiver on Android 11 using adb?

查看:64
本文介绍了如何使用 adb 在 Android 11 上触发 BroadcastReceiver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个接收器想要手动触发,但我似乎无法做到.这些是我正在使用的命令:

I have two receivers I want to trigger manually and I can't seem to do it. These are the commands I'm using:

adb -s deviceid shell am broadcast -a action android.intent.action.PHONE_STATE

adb -s deviceid shell am broadcast -a action android.intent.action.MEDIA_BUTTON

我尝试添加 -p mypackage 或 -n mypackage/myreceiver 并且它们从未被触发.我也没有在 logcat 上看到任何内容.Adb 返回 result=0,不确定是什么意思.

I've tried adding -p mypackage or -n mypackage/myreceiver and they never get triggered. I also don't see anything on logcat. Adb returns result=0, not sure what that means.

推荐答案

试试这个.

adb -s deviceid shell am broadcast -a android.intent.action.VIEW -n com.mypackage.broadcast/com.mypackage.broadcast.Broadcaster

广播类示例.

import android.content.*;
import android.widget.*;

public final class Broadcaster extends BroadcastReceiver
{   
    @Override
    public final void onReceive(final Context context, final Intent intent) {
        intent.setClass(context, Starter.class);
        //Note: without this flag android will throw a runtime exception.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        
        try {
            context.startActivity(intent);
        } catch (final Exception e) {
            Toast.makeText(context, e.getMessage(), 1) .show();
            forceStop();
        }
        forceStop();
    }
    
    private final void forceStop() {
        clearAbortBroadcast();
        //throw new RuntimeException();
        System.exit(0);
    }
    
}

Starter.java//要启动的类

Starter.java //Class that you want to start

public final class Starter extends Activity {
     @Override
      protected final void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Do something
      }
}

并且不要忘记将其放入您的清单中.

And dont forget to put this inside your manifest.

 <application
android:noHistory="true"
android:launchMode="singleInstance"
android:excludeFromRecents="true"
android:exported="true"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
        
<!-- RECEIVER -->
    <receiver 
        android:name="com.mypackage.broadcast.Broadcaster"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
            </intent-filter>
    </receiver>
...

这篇关于如何使用 adb 在 Android 11 上触发 BroadcastReceiver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆