如何取消注册Android中的广播接收器

时间:2013-06-28 22:26:55

标签: android android-widget widget

我创建了一个基本的wifi小部件。唯一的问题是,即使我从屏幕上删除/删除了小部件,它仍会继续监听wifi的变化。如果没有强制关闭/崩溃(猜测取消注册收件人)或我使用广播接收器错误,我该怎么办?

    public class WifiWidget extends AppWidgetProvider {

  WifiManager wifi;
  ConnectivityManager mgr;
  //as of 6-28 12:38am working well except when deleting widget = force close

  public void onCreate(Context context) {
      IntentFilter mFilter = new IntentFilter();
      mFilter .addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
      context.registerReceiver(WifiRec, mFilter );
     }
  @Override
  public void onEnabled(Context context){
      context.getApplicationContext().registerReceiver(this.WifiRec, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
  }


    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
        RemoteViews remoteViews;
    // Get all ids


        ComponentName thisWidget = new ComponentName(context,WifiWidget.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        for (int widgetId : allWidgetIds) { //update all instances
            wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean bgData = mgr.getBackgroundDataSetting();
            int state = 10;
            state=wifi.getWifiState();

            remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
            //Logic
            if(state==3) { // currently enabled wifi
                turnOffWifi(context,bgData);
            }

            if(state==1) { // currently disabled wifi
                turnOnWifi(context);
            }

            if(state==4) {
                reportproblem(context);
            }
            //End Logic

            // Register an onClickListener

            Intent intent = new Intent(context, WifiWidget.class);

            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
    }

    public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
        ComponentName myWidget = new ComponentName(context, WifiWidget.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        manager.updateAppWidget(myWidget, remoteViews);     
    }

    public void reportproblem(Context context) {
        updateText(context,"Error");
    }
    public void turnOnWifi(Context context) {
        updateText(context,"On");
        Toast.makeText(context, "Enabling Wifi", Toast.LENGTH_SHORT).show();
        wifi.setWifiEnabled(true);
    }
    public void turnOffWifi(Context context, boolean bgData) {
        updateText(context,"Off");
        Toast.makeText(context, "Disabling Wifi", Toast.LENGTH_SHORT).show();
        wifi.setWifiEnabled(false);
        if(bgData==true) {
            Intent sett  = new Intent("android.settings.SYNC_SETTINGS");
            sett.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(sett);
        }
    }
    public void updateText(Context context, String message) {
        RemoteViews remoteViews;
        remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
        remoteViews.setTextViewText(R.id.update,"Wi-Fi\n" + message);
        pushWidgetUpdate(context,remoteViews);
    }

    @Override
    public void onDeleted(Context context,int[] appWidgetIds) {
        //context.getApplicationContext().unregisterReceiver(WifiRec);
        //context.unregisterReceiver(WifiRec);

    }

    public void fromBRaction(Context context, Intent intent) {
        //Toast.makeText(context, "Something Changed", Toast.LENGTH_SHORT).show();
        wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        int state = 4;
        state=wifi.getWifiState();

        //Logic
        if(state==3) { // currently enabled wi-fi
            updateText(context,"On");
        }
        if(state==1) { // currently disabled wi-fi
            updateText(context,"Off");
        }
        if(state==4) { // Wi-fi Error
            updateText(context,"Error");
        }
        //End Logic
        //refresh / recall on-click listener
        RemoteViews remoteViews;
        remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
    }

    private  BroadcastReceiver WifiRec =  new BroadcastReceiver(){  
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                fromBRaction(context,intent);
            }
        }
    };
}

感谢您的帮助。 PS小部件工作得很漂亮,除非被删除。

2 个答案:

答案 0 :(得分:2)

虽然StinePike的答案在战术上是正确的,但你遇到了更大的问题:你的注册接收器会很快消失。您无法动态地从其他BroadcastReceiver注册BroadcastReceiver,因为一旦您的流程终止,动态BroadcastReceiver就会消失。

相反,请在清单中注册您的WIFI_STATE_CHANGED_ACTION收件人。如果要启用或禁用此广播的接收,请使用PackageManagersetComponentEnabledSetting()启用和禁用接收方。

答案 1 :(得分:0)

Thar部分在您的代码中发表了评论

   unregisterReceiver(WifiRec);

这是取消注册接收者的。