1/*
2 * Copyright (C) 2016 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
17package com.android.tv.settings.system;
18
19import android.app.Activity;
20import android.content.BroadcastReceiver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.pm.ResolveInfo;
25import android.os.Bundle;
26import android.os.Handler;
27import android.os.Message;
28import android.os.UserManager;
29import android.util.Log;
30
31import java.util.Objects;
32
33public class FallbackHome extends Activity {
34    private static final String TAG = "FallbackHome";
35
36    @Override
37    protected void onCreate(Bundle savedInstanceState) {
38        super.onCreate(savedInstanceState);
39        registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_USER_UNLOCKED));
40        maybeFinish();
41    }
42
43    @Override
44    protected void onDestroy() {
45        super.onDestroy();
46        unregisterReceiver(mReceiver);
47    }
48
49    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
50        @Override
51        public void onReceive(Context context, Intent intent) {
52            maybeFinish();
53        }
54    };
55
56    private void maybeFinish() {
57        if (getSystemService(UserManager.class).isUserUnlocked()) {
58            final Intent homeIntent = new Intent(Intent.ACTION_MAIN)
59                    .addCategory(Intent.CATEGORY_HOME);
60            final ResolveInfo homeInfo = getPackageManager().resolveActivity(homeIntent, 0);
61            if (Objects.equals(getPackageName(), homeInfo.activityInfo.packageName)) {
62                Log.d(TAG, "User unlocked but no home; let's hope someone enables one soon?");
63                mHandler.sendEmptyMessageDelayed(0, 500);
64            } else {
65                Log.d(TAG, "User unlocked and real home found; let's go!");
66                finish();
67            }
68        }
69    }
70
71    private Handler mHandler = new Handler() {
72        @Override
73        public void handleMessage(Message msg) {
74            maybeFinish();
75        }
76    };
77}
78