如何在Android中点击按钮启动和停止广播接收器

时间:2016-06-30 15:05:39

标签: exception permissions broadcastreceiver

我想点击按钮

开始和停止广播
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isStopped) {
                stopAnim(start);
                isStopped = false;
                checkStatus();
                IntentFilter intentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
                MainActivity.this.registerReceiver(acbroadcast , intentFilter);

                Intent i = new Intent("android.intent.action.ACTION_POWER_DISCONNECTED");
                sendBroadcast(i);
            }
        }
    });
    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isStopped) {
                stopAnim(stop);
                isStopped = true;
                checkStatus();
                MainActivity.this.unregisterReceiver(acbroadcast);
            }
        }
    });

但是当我运行应用程序时会引发异常

06-30 20:30:32.541 27577-27577/com.android.boltage.unplugbroadcast E/AndroidRuntime:
 FATAL EXCEPTION: main
 Process: com.android.boltage.unplugbroadcast, PID: 27577
 java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.ACTION_POWER_DISCONNECTED from pid=27577, uid=10149
     at android.os.Parcel.readException(Parcel.java:1546)
     at android.os.Parcel.readException(Parcel.java:1499)
     at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:3005)
     at android.app.ContextImpl.sendBroadcast(ContextImpl.java:1515)
     at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:384)
     at com.android.boltage.unplugbroadcast.MainActivity$2.onClick(MainActivity.java:69)
     at android.view.View.performClick(View.java:5076)
     at android.view.View$PerformClick.run(View.java:20279)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:135)
     at android.app.ActivityThread.main(ActivityThread.java:5930)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

1 个答案:

答案 0 :(得分:0)

我得到了一个解决方案 我们可以简单地调用服务类,它将进一步注册广播接收器,点击停止按钮将破坏服务并取消注册广播接收器 这种方法为我的问题找到了解决方案