如何使BroadCastReceiver工作



所以我几乎尝试了书中的每一个技巧来运行这件事。但徒劳无功。这就是为什么我要把所有的代码放在这里。我不明白为什么这不起作用。没有错误或类似的事情。只是,接收器永远不会启动。

<?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);
}
}

我的UI中有一个按钮,用于启动sendbroadcast方法。

如安卓官方文档中所述

从Android 8.0(API 26级(开始,系统对声明声明的接收器施加了额外的限制。

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

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

当活动暂停或取消存储时,不要忘记从接收器中注销。

最新更新