• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.car.cluster;
17 
18 import static android.car.cluster.ClusterRenderingService.LOCAL_BINDING_ACTION;
19 import static android.content.Intent.ACTION_SCREEN_OFF;
20 import static android.content.Intent.ACTION_USER_PRESENT;
21 import static android.content.Intent.ACTION_USER_SWITCHED;
22 import static android.content.Intent.ACTION_USER_UNLOCKED;
23 import static android.content.PermissionChecker.PERMISSION_GRANTED;
24 
25 import android.annotation.NonNull;
26 import android.app.ActivityManager;
27 import android.app.ActivityOptions;
28 import android.car.Car;
29 import android.car.cluster.navigation.NavigationState.NavigationStateProto;
30 import android.car.cluster.sensors.Sensors;
31 import android.content.ActivityNotFoundException;
32 import android.content.BroadcastReceiver;
33 import android.content.ComponentName;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.pm.ActivityInfo;
39 import android.content.pm.PackageManager;
40 import android.content.pm.ResolveInfo;
41 import android.graphics.Rect;
42 import android.os.Bundle;
43 import android.os.Handler;
44 import android.os.IBinder;
45 import android.os.UserHandle;
46 import android.util.Log;
47 import android.util.SparseArray;
48 import android.view.Display;
49 import android.view.InputDevice;
50 import android.view.KeyEvent;
51 import android.view.View;
52 import android.view.inputmethod.InputMethodManager;
53 import android.widget.Button;
54 import android.widget.TextView;
55 
56 import androidx.fragment.app.Fragment;
57 import androidx.fragment.app.FragmentActivity;
58 import androidx.fragment.app.FragmentManager;
59 import androidx.fragment.app.FragmentPagerAdapter;
60 import androidx.lifecycle.LiveData;
61 import androidx.lifecycle.ViewModelProvider;
62 import androidx.lifecycle.ViewModelProviders;
63 import androidx.viewpager.widget.ViewPager;
64 
65 import com.android.car.telephony.common.InMemoryPhoneBook;
66 
67 import java.lang.ref.WeakReference;
68 import java.lang.reflect.InvocationTargetException;
69 import java.net.URISyntaxException;
70 import java.util.HashMap;
71 import java.util.Map;
72 
73 /**
74  * Main activity displayed on the instrument cluster. This activity contains fragments for each of
75  * the cluster "facets" (e.g.: navigation, communication, media and car state). Users can navigate
76  * to each facet by using the steering wheel buttons.
77  * <p>
78  * This activity runs on "system user" (see {@link UserHandle#USER_SYSTEM}) but it is visible on
79  * all users (the same activity remains active even during user switch).
80  * <p>
81  * This activity also launches a default navigation app inside a virtual display (which is located
82  * inside {@link NavigationFragment}). This navigation app is launched when:
83  * <ul>
84  * <li>Virtual display for navigation apps is ready.
85  * <li>After every user switch.
86  * </ul>
87  * This is necessary because the navigation app runs under a normal user, and different users will
88  * see different instances of the same application, with their own personalized data.
89  */
90 public class MainClusterActivity extends FragmentActivity implements
91         ClusterRenderingService.ServiceClient {
92     private static final String TAG = "Cluster.MainActivity";
93 
94     private static final int NAV_FACET_ID = 0;
95     private static final int COMMS_FACET_ID = 1;
96     private static final int MEDIA_FACET_ID = 2;
97     private static final int INFO_FACET_ID = 3;
98 
99     private static final NavigationStateProto NULL_NAV_STATE =
100             NavigationStateProto.getDefaultInstance();
101     private static final int NO_DISPLAY = -1;
102 
103     private ViewPager mPager;
104     private NavStateController mNavStateController;
105     private ClusterViewModel mClusterViewModel;
106 
107     private Map<View, Facet<?>> mButtonToFacet = new HashMap<>();
108     private SparseArray<Facet<?>> mOrderToFacet = new SparseArray<>();
109 
110     private Map<Sensors.Gear, View> mGearsToIcon = new HashMap<>();
111     private InputMethodManager mInputMethodManager;
112     private ClusterRenderingService mService;
113     private VirtualDisplay mPendingVirtualDisplay = null;
114 
115     private static final int NAVIGATION_ACTIVITY_RETRY_INTERVAL_MS = 1000;
116     private static final int NAVIGATION_ACTIVITY_RELAUNCH_DELAY_MS = 5000;
117 
118     private final UserReceiver mUserReceiver = new UserReceiver();
119     private ActivityMonitor mActivityMonitor = new ActivityMonitor();
120     private final Handler mHandler = new Handler();
121     private final Runnable mRetryLaunchNavigationActivity = this::tryLaunchNavigationActivity;
122     private VirtualDisplay mNavigationDisplay = new VirtualDisplay(NO_DISPLAY, null);
123 
124     private int mPreviousFacet = COMMS_FACET_ID;
125 
126     /**
127      * Description of a virtual display
128      */
129     public static class VirtualDisplay {
130         /** Identifier of the display */
131         public final int mDisplayId;
132         /** Rectangular area inside this display that can be viewed without obstructions */
133         public final Rect mUnobscuredBounds;
134 
VirtualDisplay(int displayId, Rect unobscuredBounds)135         public VirtualDisplay(int displayId, Rect unobscuredBounds) {
136             mDisplayId = displayId;
137             mUnobscuredBounds = unobscuredBounds;
138         }
139     }
140 
141     private final View.OnFocusChangeListener mFacetButtonFocusListener =
142             new View.OnFocusChangeListener() {
143                 @Override
144                 public void onFocusChange(View v, boolean hasFocus) {
145                     if (hasFocus) {
146                         mPager.setCurrentItem(mButtonToFacet.get(v).mOrder);
147                     }
148                 }
149             };
150 
151     private ServiceConnection mClusterRenderingServiceConnection = new ServiceConnection() {
152         @Override
153         public void onServiceConnected(ComponentName name, IBinder service) {
154             Log.i(TAG, "onServiceConnected, name: " + name + ", service: " + service);
155             mService = ((ClusterRenderingService.LocalBinder) service).getService();
156             mService.registerClient(MainClusterActivity.this);
157             mNavStateController.setImageResolver(mService.getImageResolver());
158             if (mPendingVirtualDisplay != null) {
159                 // If haven't reported the virtual display yet, do so on service connect.
160                 reportNavDisplay(mPendingVirtualDisplay);
161                 mPendingVirtualDisplay = null;
162             }
163         }
164 
165         @Override
166         public void onServiceDisconnected(ComponentName name) {
167             Log.i(TAG, "onServiceDisconnected, name: " + name);
168             mService = null;
169             mNavStateController.setImageResolver(null);
170             onNavigationStateChange(NULL_NAV_STATE);
171         }
172     };
173 
174     private ActivityMonitor.ActivityListener mNavigationActivityMonitor = (displayId, activity) -> {
175         if (displayId != mNavigationDisplay.mDisplayId) {
176             return;
177         }
178         mClusterViewModel.setCurrentNavigationActivity(activity);
179     };
180 
181     /**
182      * On user switch the navigation application must be re-launched on the new user. Otherwise
183      * the navigation fragment will keep showing the application on the previous user.
184      * {@link MainClusterActivity} is shared between all users (it is not restarted on user switch)
185      */
186     private class UserReceiver extends BroadcastReceiver {
register(Context context)187         void register(Context context) {
188             IntentFilter intentFilter = new IntentFilter(ACTION_USER_UNLOCKED);
189             context.registerReceiverForAllUsers(this, intentFilter, null, null);
190         }
unregister(Context context)191         void unregister(Context context) {
192             context.unregisterReceiver(this);
193         }
194         @Override
onReceive(Context context, Intent intent)195         public void onReceive(Context context, Intent intent) {
196             if (Log.isLoggable(TAG, Log.DEBUG)) {
197                 Log.d(TAG, "Broadcast received: " + intent);
198             }
199             tryLaunchNavigationActivity();
200         }
201     }
202 
203     @Override
onCreate(Bundle savedInstanceState)204     protected void onCreate(Bundle savedInstanceState) {
205         super.onCreate(savedInstanceState);
206         Log.d(TAG, "onCreate");
207         setContentView(R.layout.activity_main);
208 
209         mInputMethodManager = getSystemService(InputMethodManager.class);
210 
211         Intent intent = new Intent(this, ClusterRenderingService.class);
212         intent.setAction(LOCAL_BINDING_ACTION);
213         bindServiceAsUser(intent, mClusterRenderingServiceConnection, 0, UserHandle.SYSTEM);
214 
215         registerFacet(new Facet<>(findViewById(R.id.btn_nav),
216                 NAV_FACET_ID, NavigationFragment.class));
217         registerFacet(new Facet<>(findViewById(R.id.btn_phone),
218                 COMMS_FACET_ID, PhoneFragment.class));
219         registerFacet(new Facet<>(findViewById(R.id.btn_music),
220                 MEDIA_FACET_ID, MusicFragment.class));
221         registerFacet(new Facet<>(findViewById(R.id.btn_car_info),
222                 INFO_FACET_ID, CarInfoFragment.class));
223         registerGear(findViewById(R.id.gear_parked), Sensors.Gear.PARK);
224         registerGear(findViewById(R.id.gear_reverse), Sensors.Gear.REVERSE);
225         registerGear(findViewById(R.id.gear_neutral), Sensors.Gear.NEUTRAL);
226         registerGear(findViewById(R.id.gear_drive), Sensors.Gear.DRIVE);
227 
228         mPager = findViewById(R.id.pager);
229         mPager.setAdapter(new ClusterPageAdapter(getSupportFragmentManager()));
230         mOrderToFacet.get(NAV_FACET_ID).mButton.requestFocus();
231         mNavStateController = new NavStateController(findViewById(R.id.navigation_state));
232 
233         IntentFilter filter = new IntentFilter();
234         filter.addAction(ACTION_USER_PRESENT);
235         filter.addAction(ACTION_SCREEN_OFF);
236         registerReceiver(new BroadcastReceiver(){
237             @Override
238             public void onReceive(final Context context, final Intent intent) {
239                 if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
240                     Log.d(TAG, "ACTION_SCREEN_OFF");
241                     mNavStateController.hideNavigationStateInfo();
242                 }
243                 else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
244                     Log.d(TAG, "ACTION_USER_PRESENT");
245                     mNavStateController.showNavigationStateInfo();
246                 }
247             }
248         }, filter);
249 
250         mClusterViewModel = new ViewModelProvider(this).get(ClusterViewModel.class);
251         mClusterViewModel.getNavigationFocus().observe(this, focus -> {
252             if (!focus) {
253                 mNavStateController.update(null);
254             }
255         });
256         mClusterViewModel.getNavigationActivityState().observe(this, state -> {
257             if (state == ClusterViewModel.NavigationActivityState.LOADING) {
258                 if (!mHandler.hasCallbacks(mRetryLaunchNavigationActivity)) {
259                     mHandler.postDelayed(mRetryLaunchNavigationActivity,
260                             NAVIGATION_ACTIVITY_RELAUNCH_DELAY_MS);
261                 }
262             } else {
263                 mHandler.removeCallbacks(mRetryLaunchNavigationActivity);
264             }
265         });
266 
267         mClusterViewModel.getSensor(Sensors.SENSOR_GEAR).observe(this, this::updateSelectedGear);
268 
269         registerSensor(findViewById(R.id.info_fuel), mClusterViewModel.getFuelLevel());
270         registerSensor(findViewById(R.id.info_speed), mClusterViewModel.getSpeed());
271         registerSensor(findViewById(R.id.info_range), mClusterViewModel.getRange());
272         registerSensor(findViewById(R.id.info_rpm), mClusterViewModel.getRPM());
273 
274         mActivityMonitor.start();
275 
276         mUserReceiver.register(this);
277 
278         InMemoryPhoneBook.init(this);
279 
280         PhoneFragmentViewModel phoneViewModel = new ViewModelProvider(this).get(
281                 PhoneFragmentViewModel.class);
282 
283         phoneViewModel.setPhoneStateCallback(new PhoneFragmentViewModel.PhoneStateCallback() {
284             @Override
285             public void onCall() {
286                 if (mPager.getCurrentItem() != COMMS_FACET_ID) {
287                     mPreviousFacet = mPager.getCurrentItem();
288                 }
289                 mOrderToFacet.get(COMMS_FACET_ID).mButton.requestFocus();
290             }
291 
292             @Override
293             public void onDisconnect() {
294                 if (mPreviousFacet != COMMS_FACET_ID) {
295                     mOrderToFacet.get(mPreviousFacet).mButton.requestFocus();
296                 }
297             }
298         });
299     }
300 
registerSensor(TextView textView, LiveData<V> source)301     private <V> void registerSensor(TextView textView, LiveData<V> source) {
302         String emptyValue = getString(R.string.info_value_empty);
303         source.observe(this, value -> {
304             // Need to check that the text is actually different, or else
305             // it will generate a bunch of CONTENT_CHANGE_TYPE_TEXT accessability
306             // actions. This will cause cts tests to fail when they waitForIdle(),
307             // and the system never idles because it's constantly updating these
308             // TextViews
309             if (value != null && !value.toString().contentEquals(textView.getText())) {
310                 textView.setText(value.toString());
311             }
312             if (value == null && !emptyValue.contentEquals(textView.getText())) {
313                 textView.setText(emptyValue);
314             }
315         });
316     }
317 
318     @Override
onDestroy()319     protected void onDestroy() {
320         super.onDestroy();
321         Log.d(TAG, "onDestroy");
322         mUserReceiver.unregister(this);
323         mActivityMonitor.stop();
324         if (mService != null) {
325             mService.unregisterClient(this);
326             mService = null;
327         }
328         unbindService(mClusterRenderingServiceConnection);
329     }
330 
331     @Override
onKeyEvent(KeyEvent event)332     public void onKeyEvent(KeyEvent event) {
333         Log.i(TAG, "onKeyEvent, event: " + event);
334 
335         // This is a hack. We use SOURCE_CLASS_POINTER here because this type of input is associated
336         // with the display. otherwise this event will be ignored in ViewRootImpl because injecting
337         // KeyEvent w/o activity being focused is useless.
338         event.setSource(event.getSource() | InputDevice.SOURCE_CLASS_POINTER);
339         mInputMethodManager.dispatchKeyEventFromInputMethod(getCurrentFocus(), event);
340     }
341 
342     @Override
onNavigationStateChange(NavigationStateProto state)343     public void onNavigationStateChange(NavigationStateProto state) {
344         Log.d(TAG, "onNavigationStateChange: " + state);
345         if (mNavStateController != null) {
346             mNavStateController.update(state);
347         }
348     }
349 
updateNavDisplay(VirtualDisplay virtualDisplay)350     public void updateNavDisplay(VirtualDisplay virtualDisplay) {
351         // Starting the default navigation activity. This activity will be shown when navigation
352         // focus is not taken.
353         startNavigationActivity(virtualDisplay);
354         // Notify the service (so it updates display properties on car service)
355         if (mService == null) {
356             // Service is not bound yet. Hold the information and notify when the service is bound.
357             mPendingVirtualDisplay = virtualDisplay;
358             return;
359         } else {
360             reportNavDisplay(virtualDisplay);
361         }
362     }
363 
reportNavDisplay(VirtualDisplay virtualDisplay)364     private void reportNavDisplay(VirtualDisplay virtualDisplay) {
365         mService.setActivityLaunchOptions(virtualDisplay.mDisplayId, ClusterActivityState
366                 .create(virtualDisplay.mDisplayId != Display.INVALID_DISPLAY,
367                         virtualDisplay.mUnobscuredBounds));
368     }
369 
370     public class ClusterPageAdapter extends FragmentPagerAdapter {
ClusterPageAdapter(FragmentManager fm)371         public ClusterPageAdapter(FragmentManager fm) {
372             super(fm);
373         }
374 
375         @Override
getCount()376         public int getCount() {
377             return mButtonToFacet.size();
378         }
379 
380         @Override
getItem(int position)381         public Fragment getItem(int position) {
382             return mOrderToFacet.get(position).getOrCreateFragment();
383         }
384     }
385 
registerFacet(Facet<T> facet)386     private <T> void registerFacet(Facet<T> facet) {
387         mOrderToFacet.append(facet.mOrder, facet);
388         mButtonToFacet.put(facet.mButton, facet);
389 
390         facet.mButton.setOnFocusChangeListener(mFacetButtonFocusListener);
391     }
392 
393     private static class Facet<T> {
394         Button mButton;
395         Class<T> mClazz;
396         int mOrder;
397 
Facet(Button button, int order, Class<T> clazz)398         Facet(Button button, int order, Class<T> clazz) {
399             this.mButton = button;
400             this.mOrder = order;
401             this.mClazz = clazz;
402         }
403 
404         private Fragment mFragment;
405 
getOrCreateFragment()406         Fragment getOrCreateFragment() {
407             if (mFragment == null) {
408                 try {
409                     mFragment = (Fragment) mClazz.getConstructors()[0].newInstance();
410                 } catch (InstantiationException | IllegalAccessException
411                         | InvocationTargetException e) {
412                     throw new RuntimeException(e);
413                 }
414             }
415             return mFragment;
416         }
417     }
418 
startNavigationActivity(VirtualDisplay virtualDisplay)419     private void startNavigationActivity(VirtualDisplay virtualDisplay) {
420         mActivityMonitor.removeListener(mNavigationDisplay.mDisplayId, mNavigationActivityMonitor);
421         mActivityMonitor.addListener(virtualDisplay.mDisplayId, mNavigationActivityMonitor);
422         mNavigationDisplay = virtualDisplay;
423         tryLaunchNavigationActivity();
424     }
425 
426     /**
427      * Tries to start a default navigation activity in the cluster. During system initialization
428      * launching user activities might fail due the system not being ready or {@link PackageManager}
429      * not being able to resolve the implicit intent. It is also possible that the system doesn't
430      * have a default navigation activity selected yet.
431      */
tryLaunchNavigationActivity()432     private void tryLaunchNavigationActivity() {
433         if (mNavigationDisplay.mDisplayId == NO_DISPLAY) {
434             if (Log.isLoggable(TAG, Log.DEBUG)) {
435                 Log.d(TAG, String.format("Launch activity ignored (no display yet)"));
436             }
437             // Not ready to launch yet.
438             return;
439         }
440         mHandler.removeCallbacks(mRetryLaunchNavigationActivity);
441 
442         ActivityInfo activityInfo = getNavigationActivity(this);
443         ComponentName navigationActivity = new ComponentName(activityInfo.packageName,
444                 activityInfo.name);
445         int userId = (activityInfo.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0
446                 ? UserHandle.USER_SYSTEM : ActivityManager.getCurrentUser();
447         mClusterViewModel.setFreeNavigationActivity(navigationActivity);
448 
449         try {
450             ClusterActivityState activityState = ClusterActivityState
451                     .create(true, mNavigationDisplay.mUnobscuredBounds);
452             Intent intent = new Intent(Intent.ACTION_MAIN)
453                     .setComponent(navigationActivity)
454                     .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
455                     .putExtra(Car.CAR_EXTRA_CLUSTER_ACTIVITY_STATE,
456                             activityState.toBundle());
457 
458             Log.d(TAG, "Launching: " + intent + " on display" + mNavigationDisplay.mDisplayId
459                     + " as user" + userId);
460             ActivityOptions activityOptions = ActivityOptions.makeBasic()
461                     .setLaunchDisplayId(mNavigationDisplay.mDisplayId);
462 
463             mService.startFixedActivityModeForDisplayAndUser(intent, activityOptions, userId);
464         } catch (ActivityNotFoundException ex) {
465             // Some activities might not be available right on startup. We will retry.
466             mHandler.postDelayed(mRetryLaunchNavigationActivity,
467                     NAVIGATION_ACTIVITY_RETRY_INTERVAL_MS);
468         } catch (Exception ex) {
469             Log.e(TAG, "Unable to start navigation activity: " + navigationActivity, ex);
470         }
471     }
472 
473     /**
474      * Returns a default navigation activity to show in the cluster.
475      * In the current implementation we obtain this activity from an intent defined in a resources
476      * file (which OEMs can overlay).
477      * When it fails to find, parse or resolve the activity, it'll throw ActivityNotFoundException.
478      */
getNavigationActivity(Context context)479     static @NonNull ActivityInfo getNavigationActivity(Context context) {
480         PackageManager pm = context.getPackageManager();
481         String intentString = context.getString(R.string.freeNavigationIntent);
482 
483         if (intentString == null) {
484             throw new ActivityNotFoundException("No free navigation activity defined");
485         }
486         Log.i(TAG, "Free navigation intent: " + intentString);
487 
488         try {
489             Intent intent = Intent.parseUri(intentString, Intent.URI_INTENT_SCHEME);
490             ResolveInfo navigationApp = pm.resolveActivity(intent,
491                     PackageManager.MATCH_DEFAULT_ONLY);
492             if (navigationApp == null) {
493                 throw new ActivityNotFoundException("Can't resolve freeNavigationIntent");
494             }
495             return navigationApp.activityInfo;
496         } catch (URISyntaxException ex) {
497             throw new ActivityNotFoundException("Unable to parse freeNavigationIntent");
498         }
499     }
500 
registerGear(View view, Sensors.Gear gear)501     private void registerGear(View view, Sensors.Gear gear) {
502         mGearsToIcon.put(gear, view);
503     }
504 
updateSelectedGear(Sensors.Gear gear)505     private void updateSelectedGear(Sensors.Gear gear) {
506         for (Map.Entry<Sensors.Gear, View> entry : mGearsToIcon.entrySet()) {
507             entry.getValue().setSelected(entry.getKey() == gear);
508         }
509     }
510 }
511