如何在android中手动停止BroadcastReceiver

发布于 2025-01-08 02:11:30 字数 4656 浏览 0 评论 0原文

我已经在 AndroidManifest.xml 中注册了我的 BroadcastReceiver,如下所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name"
    android:theme="@android:style/Theme.Light">
    <activity android:name=".WiFiDemo" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <receiver android:name="com.example.WiFiScanReceiver">
      <intent-filter>
        <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
      </intent-filter>
    </receiver>
  </application>
  <uses-sdk android:minSdkVersion="3" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
 <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"> </uses-permission>
 <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>

我想使用其他应用程序输入来停止此 BroadcastReceiver 如何以编程方式停止此接收器?

这是我的接收器代码:

public class WIFIBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()
                .equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            Intent ssIntent = new Intent(context, com.Activity.class);
            ssIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(ssIntent);
        }
    }
}

Answer:: 我添加了共享首选项复选框并保存两个字符串并在接收方法中进行验证 这是我的代码

第二个应用程序:

final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager()
        .findPreference("checkboxPref");
// ...
checkboxPref
        .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            public boolean onPreferenceChange(Preference preference,
                    Object newValue) {
                if (newValue.toString().equals("true")) {
                    // String value = sp.getString(key, null);
                    sharedPreferences = getSharedPreferences(
                            PREFS_READ, Context.MODE_WORLD_READABLE);
                    Editor prefsPrivateEditor = sharedPreferences.edit();
                    prefsPrivateEditor.putString(KEY_READ1, "true");
                    prefsPrivateEditor.commit();
                    Toast.makeText(getApplicationContext(),
                            "CB: " + "true", Toast.LENGTH_SHORT).show();
                } else {
                    sharedPreferences = getSharedPreferences(
                            PREFS_READ, Context.MODE_WORLD_READABLE);
                    Editor prefsPrivateEditor = sharedPreferences.edit();
                    prefsPrivateEditor.putString(KEY_READ1, "false");
                    prefsPrivateEditor.commit();
                    Toast.makeText(getApplicationContext(),
                            "CB: " + "false", Toast.LENGTH_SHORT)
                            .show();
                }
                return true;
            }
        });

onReceive 方法内验证第一个应用程序中的代码:

public class WIFIBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()
                .equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            sharedPreferences = otherAppsContext.getSharedPreferences(
                    PREFS_READ, Context.MODE_WORLD_WRITEABLE);
            String scaningAction = sharedPreferences.getString(KEY_READ1, null);
            if (scaningAction.equals("true")) {
                Intent ssIntent = new Intent(context, com.Activity.class);
                ssIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(ssIntent);
            }
        }
    }
}

这是我的需要。但我无法注销广播接收器。如果没有任何活动,这个答案将对某人有所帮助。

I have registered my BroadcastReceiver in AndroidManifest.xml like this

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name"
    android:theme="@android:style/Theme.Light">
    <activity android:name=".WiFiDemo" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <receiver android:name="com.example.WiFiScanReceiver">
      <intent-filter>
        <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
      </intent-filter>
    </receiver>
  </application>
  <uses-sdk android:minSdkVersion="3" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
 <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"> </uses-permission>
 <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>

I want to stop this BroadcastReceiver using other application input how to stop this receiver programmatically ?

here is my receiver code:

public class WIFIBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()
                .equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            Intent ssIntent = new Intent(context, com.Activity.class);
            ssIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(ssIntent);
        }
    }
}

Answer::
I have add sharedprefernce checkbox and save the two string and validate in on receive method
here is my code

second application :

final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager()
        .findPreference("checkboxPref");
// ...
checkboxPref
        .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            public boolean onPreferenceChange(Preference preference,
                    Object newValue) {
                if (newValue.toString().equals("true")) {
                    // String value = sp.getString(key, null);
                    sharedPreferences = getSharedPreferences(
                            PREFS_READ, Context.MODE_WORLD_READABLE);
                    Editor prefsPrivateEditor = sharedPreferences.edit();
                    prefsPrivateEditor.putString(KEY_READ1, "true");
                    prefsPrivateEditor.commit();
                    Toast.makeText(getApplicationContext(),
                            "CB: " + "true", Toast.LENGTH_SHORT).show();
                } else {
                    sharedPreferences = getSharedPreferences(
                            PREFS_READ, Context.MODE_WORLD_READABLE);
                    Editor prefsPrivateEditor = sharedPreferences.edit();
                    prefsPrivateEditor.putString(KEY_READ1, "false");
                    prefsPrivateEditor.commit();
                    Toast.makeText(getApplicationContext(),
                            "CB: " + "false", Toast.LENGTH_SHORT)
                            .show();
                }
                return true;
            }
        });

validating code in first application inside of onReceive method:

public class WIFIBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()
                .equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            sharedPreferences = otherAppsContext.getSharedPreferences(
                    PREFS_READ, Context.MODE_WORLD_WRITEABLE);
            String scaningAction = sharedPreferences.getString(KEY_READ1, null);
            if (scaningAction.equals("true")) {
                Intent ssIntent = new Intent(context, com.Activity.class);
                ssIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(ssIntent);
            }
        }
    }
}

this is my need. But I am not able to unregister the broadcast receiver. with out activity any this answer will helpful for some one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

撩发小公举 2025-01-15 02:11:30

您可以使用此方法:

ComponentName receiver = new ComponentName(context, myReceiver.class);

PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP)

有关详细信息,请访问此处

You can use this :

ComponentName receiver = new ComponentName(context, myReceiver.class);

PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP)

For more information visit here.

一身软味 2025-01-15 02:11:30

像这样:

PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(WiFiScanReceiver,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);

Like this:

PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(WiFiScanReceiver,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);
溺深海 2025-01-15 02:11:30

大多数情况下,您必须在 onResume() 方法中注册 BroadCastReceiver,因为它是 Activity 的运行状态。我们可以在 Activity 的 onPause()(即 Activity 的 Stopped State)中取消注册它。您可以从 广播接收器 阅读更多相关信息

Mostly you have to register your BroadCastReceiver in your onResume() method as it is the Running State of Activity. And we can unregister it inside the onPause() which is Stopped State of an Activity. You can read more about it from Broadcast Receivers

温暖的光 2025-01-15 02:11:30

我猜想具有偏好的代码位于某些偏好活动中。因此,让您的接收器保持原来的样子,并使用类似的内容:

public class YourSettingsActivity extends PreferenceActivity {

    OnPreferenceChangeListener onPreferenceChangeListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onPreferenceChangeListener = new OnPreferenceChangeListener() {

            public boolean onPreferenceChange(Preference preference,
                    Object newValue) {
                if (newValue instanceof Boolean) {
                    final boolean enable = (Boolean) newValue;
                    PackageManager pacman = getPackageManager();
                    final ComponentName componentName = new ComponentName(
                            "com.example.yourapp1", WIFIBroadcastReceiver.class);
                    final int state = (enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                            : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
                    pacman.setComponentEnabledSetting(componentName, state,
                            PackageManager.DONT_KILL_APP);
                    Toast.makeText(getApplicationContext(), "CB: " + enable,
                            Toast.LENGTH_SHORT).show();
                    return true;
                }
                return false;
            }
        };
        @SuppressWarnings("deprecation")
        final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager()
                .findPreference("checkboxPref");
        checkboxPref.setOnPreferenceChangeListener(onPreferenceChangeListener);
    }
}

您可能会遇到安全异常 - 请参阅此处添加权限:

<!-- Allows an application to change whether an application component (other than
      its own) is enabled or not. -->
<permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"
    android:label="@string/permlab_changeComponentState"
    android:description="@string/permdesc_changeComponentState"
    android:protectionLevel="signatureOrSystem" />

另外,您在排队时必须小心:

final ComponentName componentName = new ComponentName(
                            "com.example.yourapp1", WIFIBroadcastReceiver.class);

如果这解决了问题,请回帖

I guess the code with the preference is in some preference activity. So leave your receiver as it was originally and use something like :

public class YourSettingsActivity extends PreferenceActivity {

    OnPreferenceChangeListener onPreferenceChangeListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onPreferenceChangeListener = new OnPreferenceChangeListener() {

            public boolean onPreferenceChange(Preference preference,
                    Object newValue) {
                if (newValue instanceof Boolean) {
                    final boolean enable = (Boolean) newValue;
                    PackageManager pacman = getPackageManager();
                    final ComponentName componentName = new ComponentName(
                            "com.example.yourapp1", WIFIBroadcastReceiver.class);
                    final int state = (enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                            : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
                    pacman.setComponentEnabledSetting(componentName, state,
                            PackageManager.DONT_KILL_APP);
                    Toast.makeText(getApplicationContext(), "CB: " + enable,
                            Toast.LENGTH_SHORT).show();
                    return true;
                }
                return false;
            }
        };
        @SuppressWarnings("deprecation")
        final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager()
                .findPreference("checkboxPref");
        checkboxPref.setOnPreferenceChangeListener(onPreferenceChangeListener);
    }
}

You will probably run into security exceptions - see here for adding permissions :

<!-- Allows an application to change whether an application component (other than
      its own) is enabled or not. -->
<permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"
    android:label="@string/permlab_changeComponentState"
    android:description="@string/permdesc_changeComponentState"
    android:protectionLevel="signatureOrSystem" />

Also you will have to be careful in line :

final ComponentName componentName = new ComponentName(
                            "com.example.yourapp1", WIFIBroadcastReceiver.class);

Post back if this solved it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文