如何通过adb在Android 11上触发一个广播接收器?

3
我有两个接收器需要手动触发,但似乎无法完成。以下是我使用的命令:
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,不确定其含义。
1个回答

5
尝试这个。
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 //要启动的类

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

不要忘记将此放入您的清单中。

 <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>
...

这个方法有效,但是要用-n而不是-p。我会将其标记为正确的,希望你会进行编辑,或者其他人能看到这个评论。 - casolorz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接