【问题标题】:Android : Get the screen rotation from a BroadcastReceiverAndroid:从广播接收器获取屏幕旋转
【发布时间】:2016-03-18 13:58:19
【问题描述】:

我有一个 AlarmManager,每 5 分钟执行一次 Intent Broadcast

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 300000, PendingIntent.getBroadcast(context, 0, new Intent(context, Sensors.class), 0));

BroadcastReceiver的onReceive方法中,我需要知道设备方向(0°、90°、180°、270°):

int orientation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

一切正常。但是当我最小化或关闭应用程序时,即使设备水平放置,屏幕的旋转总是返回 0°(android 主屏幕的方向)。

我如何从 BroadcastReceiver 知道设备的旋转,而与应用或设备的状态无关?

【问题讨论】:

    标签: android broadcastreceiver alarmmanager screen-orientation android-broadcast


    【解决方案1】:

    我终于用加速度计解决了这个问题:

    SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    
    if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
    final SensorEventListener sensorEventListener = new SensorEventListener() {
        public void onSensorChanged(SensorEvent event) {
            sensorManager.unregisterListener(this);
    
            int orientation;
    
            // Vertical
            if (Math.abs(event.values[1]) > Math.abs(event.values[0]) && Math.abs(event.values[1]) > Math.abs(event.values[2]))
                if (event.values[1] > 0)
                    orientation = 0; // Head Up
                else
                    orientation = 180; // Head Down
    
            // Horizontal
            else if (Math.abs(event.values[0]) > Math.abs(event.values[1]) && Math.abs(event.values[0]) > Math.abs(event.values[2]))
                if (event.values[0] > 0)
                    orientation = 90; // Left
                else
                    orientation = 270; // Right
    
            // Flat
            else
                orientation = 0;
        }
    
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
    
        }
    };
    
    sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
    }
    

    【讨论】:

      【解决方案2】:

      This tutorial 可能对未来的搜索者有用。

      要完成这项工作,首先需要创建一个继承自 BroadcastReceiver 并实现 onReceive() 方法的类。这个方法告诉BroadcastReceiver 在检测到正确的 Intent 时应该做什么。因此,目前,正在定义 BroadcastReceiver 类的子类,以便在触发 BroadcastReceiver 时必须执行的代码。在本教程的后面,您将了解如何过滤意图以检测方向变化。为简单起见,下面的代码检测设备的方向变化和角度,并在 Toast 通知中显示此信息。代码如下:

      package fortyonepost.com.orientationbrec;   
      
      import android.content.BroadcastReceiver;  
      import android.content.Context;  
      import android.content.Intent;  
      import android.content.res.Configuration;  
      import android.view.Surface;  
      import android.view.WindowManager;  
      import android.widget.Toast;  
      
      public class OrientationBroadcastReceiver extends BroadcastReceiver  
      {  
          //An integer that holds the value of the orientation given by the current configuration  
          private int configOrientation;  
      
          //A WindowManager object that will act as a handle to the window service  
          private WindowManager wm;  
          //An integer that holds the value of the orientation (in degrees) given by the window service  
          private int windowServOrientation;  
      
          @Override  
          public void onReceive(Context context, Intent intent)  
          {  
              //Get the orientation from the current configuration object  
              configOrientation = context.getResources().getConfiguration().orientation;  
      
              //Display the current orientation using a Toast notification  
              switch (configOrientation)  
              {  
                  case Configuration.ORIENTATION_LANDSCAPE:  
                  {  
                      Toast.makeText(context, "Orientation is LANDSCAPE", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
                  case Configuration.ORIENTATION_PORTRAIT:  
                  {  
                      Toast.makeText(context, "Orientation is PORTRAIT", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
                  case Configuration.ORIENTATION_SQUARE:  
                  {  
                      Toast.makeText(context, "Orientation is SQUARE", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
      
                  case Configuration.ORIENTATION_UNDEFINED:  
                  default:  
                  {  
                      Toast.makeText(context, "Orientation is UNDEFINED", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
              }   
      
              //Get a handle to the Window Service  
              wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);  
              //Query the current orientation made available by the Window Service  
              //The getOrientation() method is deprecated. Instead, use getRotation() when targeting Android API 8 (Android 2.2 - Froyo) or above.  
              windowServOrientation =  wm.getDefaultDisplay().getOrientation();  
      
              //Display the current orientation using a Toast notification  
              switch (windowServOrientation)  
              {  
                  case Surface.ROTATION_0:  
                  {  
                      Toast.makeText(context, "Rotation is 0 degrees.", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
      
                  case Surface.ROTATION_90:  
                  {  
                      Toast.makeText(context, "Rotation is 90 degrees.", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
      
                  case Surface.ROTATION_180:  
                  {  
                      Toast.makeText(context, "Rotation is 180 degrees.", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
      
                  case Surface.ROTATION_270:  
                  {  
                      Toast.makeText(context, "Rotation is 270 degrees.", Toast.LENGTH_SHORT).show();  
                      break;  
                  }  
              }  
          }  
      }
      

      这是负责注册的 Activity 和 unregistering BroadcastReceiver。代码如下:

      package fortyonepost.com.orientationbrec;  
      
      import android.app.Activity;  
      import android.content.Intent;  
      import android.content.IntentFilter;  
      import android.os.Bundle;  
      
      public class OrientationBroadcastReceiverActivity extends Activity  
      {  
          //Create and initialize an OrientationBroadcastReceiver object  
          private OrientationBroadcastReceiver orientationBR = new OrientationBroadcastReceiver();  
          //Create and initialize a new IntentFilter  
          private IntentFilter orientationIF = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED);  
      
          /** Called when the activity is first created. */  
          @Override  
          public void onCreate(Bundle savedInstanceState)  
          {  
              super.onCreate(savedInstanceState);  
              setContentView(R.layout.main);  
          }  
      
          @Override  
          protected void onResume()  
          {  
              //Register the Orientation BroadcasReceiver  
              this.registerReceiver(orientationBR, orientationIF);  
              super.onResume();  
          }  
      
          @Override  
          protected void onPause()  
          {  
              //Unregister the Orientation BroadcasReceiver to avoid a BroadcastReceiver leak  
              this.unregisterReceiver(orientationBR);  
              super.onPause();  
          }  
      }  
      

      【讨论】:

        【解决方案3】:

        也许this 就是您要搜索的内容。

        context.getResources().getConfiguration().orientation
        

        this way你可以得到实时变化。

        【讨论】:

        • 谢谢@M66B,但它返回“风景”或“肖像”。我需要知道旋转(0°、90°、180° 或 270°)
        猜你喜欢
        • 2012-03-17
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多