我如何让这个BroadCastReceiver工作?

问题描述 投票:0回答:1

我几乎试过了书中所有的技巧来让这个东西运行。但都是徒劳无功,所以我把所有的代码都放在了这里。我不明白为什么这东西不能用,没有错误或类似的东西。只是接收器从来没有启动过

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastmannankatta">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcastmannankatta" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
package com.example.broadcastmannankatta;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context, "YEAHA", Toast.LENGTH_LONG).show();
    }
}

package com.example.broadcastmannankatta;

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

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void sendbroadcast(View view) {
        Intent bIntent = new Intent();
        bIntent.setAction("com.example.broadcastmannankatta");
        sendBroadcast(bIntent);
    }
}

我的用户界面有一个按钮,可以启动发送广播的方法。

android broadcast receiver
1个回答
0
投票

正如在解释 安卓官方文档

从Android 8.0(API级别26)开始,系统对manifest-declared接收器施加了额外的限制。

如果您的应用程序的目标是 Android 8.0 或更高版本,您不能使用清单为大多数隐式广播(不专门针对您的应用程序的广播)声明接收器。当用户主动使用您的应用程序时,您仍然可以使用上下文注册的接收器。

因此,请按照链接中的说明注册到您的自定义接收器。上下文记录者

当活动被暂停或破坏时,不要忘记从你的接收器中取消注册。

© www.soinside.com 2019 - 2024. All rights reserved.