如何在主屏幕小部件中检测方向变化?

use*_*239 5 android

我正在编写一个主屏幕小部件,并希望在设备方向从纵向更改为横向或其他方式时更新主屏幕小部件.我该怎么做?

目前,我尝试像下面的代码一样重新配置CONFIGURATION_CHANGED操作,但Android不允许我这样做,说"不允许IntentReceiver组件注册接收意图".有人能帮我吗?谢谢.

public class MyWidget extends AppWidgetProvider {

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        this.registerReceiver(this, new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    }
Run Code Online (Sandbox Code Playgroud)

Ema*_*lin 8

我知道这是一个老问题,但确实有一种比将更新委托给IntentService更简单的方法.处理方向更改的方法是在应用程序中侦听配置更改,并向窗口小部件广播ACTION_APPWIDGET_UPDATE.

将Application类添加到您的应用程序

public class MyApplication extends Application {

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // create intent to update all instances of the widget
        Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidget.class);

        // retrieve all appWidgetIds for the widget & put it into the Intent
        AppWidgetManager appWidgetMgr = AppWidgetManager.getInstance(this);
        ComponentName cm = new ComponentName(this, MyWidget.class);
        int[] appWidgetIds = appWidgetMgr.getAppWidgetIds(cm);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        // update the widget
        sendBroadcast(intent);
    }
}
Run Code Online (Sandbox Code Playgroud)

只要发生配置更改,就会调用该方法,其中一个是方向更改.您可以通过仅在方向更改时进行广播而不是例如更改系统语言来改进方法.该方法基本上向您的窗口小部件的所有实例发送更新广播.

在清单中定义MyApplication

<application
    android:name="yourpackagename.MyApplication"
    android:description="@string/app_name"
    android:label="@string/app_name"
    android:icon="@drawable/app_icon">

    <!-- here go your Activity definitions -->

</application>
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但仅当您的应用程序在后台运行时才有效。一旦你的应用程序被 Android 框架杀死,它就无法运行。 (4认同)

jqp*_*liq 3

您可能不需要这样做。您可以使用layout和layout-land文件夹通过xml在每个方向提供不同的布局,而无需手动检测旋转。但是,您不应该在每个方向上执行任何功能不同的操作,因为许多设备无法旋转主屏幕,并且它们将无法访问您添加的任何功能。