如何更新widget被接收了一次广播意图CONNECTIVITY_CHANGE(How to upd

2019-07-30 03:01发布

我想更新的窗口小部件的文本和它的颜色,只要网络的分组数据连接的变化。 即使是这个小工具可以启用/禁用网络数据包的数据。 广播接收机android.net.conn.CONNECTIVITY_CHANGE一直寄存器Android清单文件的onReceive()中的AppWidgetProvider类已经被覆盖。

我注意到一个很奇怪的现象,每当我打开/关闭连接的onReceive()是越来越触发两次。 在第一种情况下,我收到NetworkInfo对象,但在二审我没有收到信息的实例。 但是,当我能够通过系统设置的onReceive /关闭连接()是越来越触发一次NetworkInfo对象为null。

这里是我的清单文件。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rakesh.simplewidget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <!-- Permissions -->
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <!-- Widget Broadcast receiver -->
        <receiver
            android:name=".ExampleAppWidgetProvider"
            android:label="Widget ErrorBuster" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget1_info" />
        </receiver>
        <service android:name=".UpdateWidgetService"></service>
    </application>
</manifest>

我的AppWidgetProvider类是如下。

public class ExampleAppWidgetProvider extends AppWidgetProvider {

 int[] mAppWidgetIds;

 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

  final int N = appWidgetIds.length;
  this.mAppWidgetIds = appWidgetIds;


  // Get all ids
  ComponentName thisWidget = new ComponentName(context,
   ExampleAppWidgetProvider.class);
  int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

  // Build the intent to call the service
  Intent intent = new Intent(context.getApplicationContext(),
   UpdateWidgetService.class);
  intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

  // Update the widgets via the service
  context.startService(intent);
 }

 @Override
 public void onReceive(Context context, Intent intent) {
  super.onReceive(context, intent);
  NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

  StringBuilder str = new StringBuilder();
  if (info != null) {
   str.append(" info is NULL");
  }
  if (checkConnectivityState(context)) {
   str.append("; data is enable");
  } else {
   str.append("; data is disable");
  }
  Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
 }

 public static void updateAppWidget(Context context,
  int[] appWidgetIds, boolean enable) {
  if (appWidgetIds == null) {
   return;
  }
  if (appWidgetIds.length > 0) {

   AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
   RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget1);
   if (enable) {
    updateViews.setTextColor(R.id.BtEnableDisable, Color.GREEN);
    updateViews.setTextViewText(R.id.BtEnableDisable, "Enabled");

   } else {
    updateViews.setTextColor(R.id.BtEnableDisable, Color.GRAY);
    updateViews.setTextViewText(R.id.BtEnableDisable, "Disabled");
   }
   appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
   Toast.makeText(context, "updateAppWidget() ", Toast.LENGTH_SHORT).show();

  }
 }

 private boolean checkConnectivityState(Context context) {
  final TelephonyManager telephonyManager = (TelephonyManager) context
   .getSystemService(Context.TELEPHONY_SERVICE);
  return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED;

 }
}

服务类用于允许/禁止网络分组数据连接。

public class UpdateWidgetService extends Service {
    private static final String LOG = "de.vogella.android.widget.example";

    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(LOG, "Called");
        // Create some random data

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
                .getApplicationContext());

        int[] allWidgetIds = intent
                .getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

        ComponentName thisWidget = new ComponentName(getApplicationContext(),
                ExampleAppWidgetProvider.class);
        int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
        Log.w(LOG, "From Intent" + String.valueOf(allWidgetIds.length));
        Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length));

        for (int widgetId : allWidgetIds) {
            // Create some random data
            int number = (new Random().nextInt(100));

            RemoteViews remoteViews = new RemoteViews(this
                    .getApplicationContext().getPackageName(),
                    R.layout.widget1);
            Log.w("WidgetExample", String.valueOf(number));
            EnableDisableConnectivity edConn = new EnableDisableConnectivity(this.getApplicationContext());
            edConn.enableDisableDataPacketConnection(!checkConnectivityState(this.getApplicationContext()));

            // Register an onClickListener
            Intent clickIntent = new Intent(this.getApplicationContext(),
                    ExampleAppWidgetProvider.class);

            clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
                    allWidgetIds);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.BtEnableDisable, pendingIntent);
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
        stopSelf();

        super.onStart(intent, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private boolean checkConnectivityState(Context context){
        final TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED;

    }
}

我也试图与广播接收器类有我收到的NetworkInfo每当有连接改变。 但我不知道如何更新从广播接收器窗口小部件的文字/色彩。

是否有任何其他方式一次我收到CONNECTIVITY_CHANGE意图我可以更新窗口小部件的文字/色彩?

编辑:

我无法想通了,为什么我在获得两个CONNECTIVITY_CHANGE意图AppWidgetProvider ,但我必须学会如何更新从广播接收器窗口小部件及以下的代码。

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        NetworkInfo info = (NetworkInfo)intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);

        if(info.getType() == ConnectivityManager.TYPE_MOBILE){

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                    R.layout.widget1);

            if(info.isConnectedOrConnecting()){
                Toast.makeText(context, "Data packet enabled", Toast.LENGTH_SHORT).show();
                Log.d("RK","Mobile data is enabled");
                remoteViews.setTextColor(R.id.BtEnableDisable, Color.GREEN);
                remoteViews.setTextViewText(R.id.BtEnableDisable, "Enabled");
            }else{
                Toast.makeText(context, "Data packet disabled", Toast.LENGTH_SHORT).show();
                Log.e("RK","Mobile data is disconnected");
                remoteViews.setTextColor(R.id.BtEnableDisable, Color.BLACK);
                remoteViews.setTextViewText(R.id.BtEnableDisable,"Disabled");
            }

            ComponentName thiswidget = new ComponentName(context, ExampleAppWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(context);
            manager.updateAppWidget(thiswidget, remoteViews);

        }
    }

}

如果有人知道为什么我获得两个CONNECTIVITY_CHANGE意向,请在这里分享你的看法。 你帮助会在这里得到真正的重视。

Answer 1:

现在,我已经发现为什么onReceive()按钮被点击时启用/禁用网络被调用两次。 1.第一次被调用时APPWIDGET_UPDATE意向广播。 2.第二次它被调用时CONNECTIVITY_CHANGE意向广播。

反正我能够更新来自广播接收器的小部件,源代码已经贴在上面的帖子。



文章来源: How to update widget once broadcast intent CONNECTIVITY_CHANGE is received