original source: https://developer.android.com/training/wearables/apps/always-on.html

Keeping Your App Visible

Android Wear devices running Android version 5.1 or higher allow apps to remain in the foreground while saving battery power.

Important: The 27.0.0 version of the Android Support Library enables a new way to support ambient mode that uses the AmbientMode(새로운방버) class rather than the WearableActivity(기존의방법) class. You can decide whether you want to use

Configure your project

기본적으로 ambient상태에서도 app이 작동하게 하기 위해서는 기본적으로 설정작업이 필요하다.

  1. Create or update your project based on the configurations on the Creating and Running a Wearable App page.
  2. Add the WAKE_LOCK permission to the Android Manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK" />

Ambient Mode Using the AmbientMode Class

AmbientMode 클래스 사용의 장점

Note: The AmbientMode.attachAmbientSupport() method attaches a headless fragment to the Activity class or subclass that you provide, and subsequent calls to FragmentManager.getFragments() return a reference to this fragment (which is not intended to be used in any way)

AmbientMode class를 이용한 방법

1. Create a subclass of one of the Activity classes.

2. 

public class MainActivity extends Activity implements AmbientMode.AmbientCallbackProvider {
   …
   @Override
   public AmbientMode.AmbientCallback getAmbientCallback() {
       return new MyAmbientCallback();
   }
   …
}

3. 

This method returns anAmbientMode.AmbientController. The controller allows you to check the ambient state outside of the callbacks

public class MainActivity extends Activity implements AmbientMode.AmbientCallbackProvider {
   …
   /*
    * Declare an ambient mode controller, which will be used by
    * the activity to determine if the current mode is ambient.
    */
   private AmbientMode.AmbientController mAmbientController;
   …
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   ...
       mAmbientController = AmbientMode.attachAmbientSupport(this);
   }
   ...
}

4.

Create an inner class that extends the AmbientCallback class in order to act on ambient events

private class MyAmbientCallback extends AmbientMode.AmbientCallback {
   @Override
   public void onEnterAmbient(Bundle ambientDetails) {
            // Handle entering ambient mode
   }

   @Override
   public void onExitAmbient() {
     // Handle exiting ambient mode
    }

   @Override
   public void onUpdateAmbient() {
     // Update the content
   }
}

Ambient Mode Using the WearableActivity Class

       Create an activity that supports ambient mode

1.Create an activity that extends WearableActivity.

2. In the onCreate() method of your activity, call the setAmbientEnabled() method.

public class MainActivity extends WearableActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   setAmbientEnabled();
   ...
}

       Handle transitions between modes

When the activity switches to ambient mode, the system calls the onEnterAmbient() method in your wearable activity.

예) 

@Override
public void onEnterAmbient(Bundle ambientDetails) {
   super.onEnterAmbient(ambientDetails);

   mStateTextView.setTextColor(Color.WHITE);
   mStateTextView.getPaint().setAntiAlias(false);
}

the activity switches from ambient mode to interactive mode.

예)

@Override
public void onExitAmbient() {
   super.onExitAmbient();

   mStateTextView.setTextColor(Color.GREEN);
   mStateTextView.getPaint().setAntiAlias(true);
}

       Update Content in Ambient Mode

You should strongly consider only overriding the onUpdateAmbient() method to update the screen once a minute in ambient mode. If your app requires more frequent updates, take into consideration that there is a trade-off between battery life and the frequency of updates. To realize battery savings, updates should be no more than once every 10 seconds.

                  Update once a minute (일분에 한번만 업데이트하는 경우)

onUpdateAmbient(), that allows you to update the screen

예)

@Override
public void onUpdateAmbient() {
   super.onUpdateAmbient();
   // Update the content
}

                 

Update more frequently (좀더 자주 업데이트해야 하는 경우)

use an AlarmManager object to wake the processor

사용방법

  1. Prepare the alarm manager.
  2. Set the frequency of the updates.
  3. Schedule the next update when the activity switches to ambient mode or is currently in ambient mode.
  4. Cancel the alarm when the activity switches to interactive mode or the activity is stopped

Note: The alarm manager may create new instances of your activity as they are triggered. To prevent this situation, ensure that your activity is declared with the android:launchMode="singleInstance" parameter in the manifest.

                            1. Prepare the alarm manager

// Action for updating the display in ambient mode, per our custom refresh cycle.
private static final String AMBIENT_UPDATE_ACTION = "com.your.package.action.AMBIENT_UPDATE";

private AlarmManager mAmbientUpdateAlarmManager;
private PendingIntent mAmbientUpdatePendingIntent;
private BroadcastReceiver mAmbientUpdateBroadcastReceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   setAmbientEnabled();

   mAmbientUpdateAlarmManager =
       (AlarmManager) getSystemService(Context.ALARM_SERVICE);

   Intent ambientUpdateIntent = new Intent(AMBIENT_UPDATE_ACTION);

   mAmbientUpdatePendingIntent = PendingIntent.getBroadcast(
       this, 0, ambientUpdateIntent, PendingIntent.FLAG_UPDATE_CURRENT);

   mAmbientUpdateBroadcastReceiver = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
           refreshDisplayAndSetNextUpdate();
       }
   };
   ...
}
@Override
public void onResume() {
   super.onResume();
   IntentFilter filter = new IntentFilter(AMBIENT_UPDATE_ACTION);
   registerReceiver(mAmbientUpdateBroadcastReceiver, filter);
       ...
}

@Override
public void onPause() {
   super.onPause();
   unregisterReceiver(mAmbientUpdateBroadcastReceiver);
   mAmbientUpdateAlarmManager.cancel(mAmbientUpdatePendingIntent);
   ...
}

                             2.

Update screen and schedule data updates

// Milliseconds between waking processor/screen for updates
private static final long AMBIENT_INTERVAL_MS = TimeUnit.SECONDS.toMillis(20);
private void refreshDisplayAndSetNextUpdate() {
   if (isAmbient()) {
       // Implement data retrieval and update the screen for ambient mode
   } else {
       // Implement data retrieval and update the screen for interactive mode
   }
   long timeMs = System.currentTimeMillis();
   // Schedule a new alarm
   if (isAmbient()) {
       // Calculate the next trigger time
       long delayMs = AMBIENT_INTERVAL_MS - (timeMs % AMBIENT_INTERVAL_MS);
       long triggerTimeMs = timeMs + delayMs;
       mAmbientStateAlarmManager.setExact(
           AlarmManager.RTC_WAKEUP,
           triggerTimeMs,
           mAmbientStatePendingIntent);
   } else {
       // Calculate the next trigger time for interactive mode
   }
}

                               3.

Schedule the next alarm

@Override
public void onEnterAmbient(Bundle ambientDetails) {
   super.onEnterAmbient(ambientDetails);
   refreshDisplayAndSetNextUpdate();
}

@Override
public void onUpdateAmbient() {
   super.onUpdateAmbient();
   refreshDisplayAndSetNextUpdate();
}

                                 4.

Cancel the alarm

@Override
public void onExitAmbient() {
   super.onExitAmbient();
   mAmbientStateAlarmManager.cancel(mAmbientUpdatePendingIntent);
}
@Override
public void onDestroy() {
   mAmbientStateAlarmManager.cancel(mAmbientUpdatePendingIntent);
   super.onDestroy();
}

Maintain Backward-compatibility

Android versions prior to 5.1 에서는 위의 방법이 적용되지 않으며 보통 activity처럼 행동한다.

ambient mode 모드가 되는 순간 작동하는 순간 activity는 exit하게 되고 home screen 으로 이동한다.

Android versions prior to 5.1 을 개발하는 앱이 지원하지 않는 경우 

<uses-library android:name="com.google.android.wearable" android:required="true" />

를 manifest에 작성해서 설치를 막는다.

Comments are closed.

Post Navigation