【问题标题】:Why isn't the broadcast receiver working? I have tried quite a few solutions posted in this site as well in others however it isn't working. Help me [duplicate]为什么广播接收器不工作?我已经尝试了很多在这个网站以及其他网站上发布的解决方案,但是它不起作用。帮帮我[重复]
【发布时间】:2018-04-06 15:31:20
【问题描述】:

这是我在广播接收器类中的代码

package com.example.manjit.myapplication;

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

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "working!!", Toast.LENGTH_SHORT).show();
    }
}

并且清单文件包含以下代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.manjit.myapplication">
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <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">
        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
            </intent-filter>
        </receiver>
    </application>
</manifest>

我已经尝试了许多操作的代码,例如action android:name="android.intent.action.HEADSET_PLUG",但没有显示吐司。请帮帮我。我试过在 Lolipop 上跑步

【问题讨论】:

  • 什么不起作用?
  • 你在哪个操作系统上试过这个?
  • 我在Android 5.1.1上试过了..没有显示吐司
  • 您需要在安装后至少运行一次的应用中添加Activity,以使您的应用退出已停止状态。在那之前,您的接收器将无法工作。此外,您无法在清单注册的接收器中接收HEADSET_PLUG 广播。

标签: java android xml broadcastreceiver


【解决方案1】:

尝试添加两个动作:

<receiver android:name=".MyReceiver"
        android:enabled="true"
        android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
    </intent-filter>
</receiver>

然后像这样改变你的接收器:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == Intent.ACTION_POWER_CONNECTED) {
            Toast.makeText(context, "ACTION_POWER_CONNECTED", Toast.LENGTH_SHORT).show();
        } else if (intent.getAction() == Intent.ACTION_POWER_DISCONNECTED) {
            Toast.makeText(context, "ACTION_POWER_DISCONNECTED", Toast.LENGTH_SHORT).show();
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2023-01-13
  • 2011-04-07
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多