vijai1996 / screenrecorder

NOTICE: This repository has moved to gitlab
https://gitlab.com/vijai/screenrecorder
GNU Affero General Public License v3.0
123 stars 49 forks source link

I am trying add SettingsPrefrenceFragment to activity not asking runtime permission #60

Closed bharathnr21 closed 6 years ago

bharathnr21 commented 6 years ago
public class SettingActivity extends AppCompatPrefernceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
         getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsPreferenceFragment()).commit();
    }

    public static class SettingsPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
            , PermissionResultListener, OnDirectorySelectedListerner {

        SharedPreferences prefs;

        private ListPreference res;

        private CheckBoxPreference recaudio;

        private CheckBoxPreference floatingControl;

        private FolderChooser dirChooser;

        private MainActivity activity;

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings);

            setPermissionListener();

            String defaultSaveLoc = (new File(Environment
                    .getExternalStorageDirectory() + File.separator + Const.APPDIR)).getPath();

            prefs = getPreferenceScreen().getSharedPreferences();
            res = (ListPreference) findPreference(getString(R.string.res_key));
            ListPreference fps = (ListPreference) findPreference(getString(R.string.fps_key));
            ListPreference bitrate = (ListPreference) findPreference(getString(R.string.bitrate_key));
            recaudio = (CheckBoxPreference) findPreference(getString(R.string.audiorec_key));
            ListPreference filenameFormat = (ListPreference) findPreference(getString(R.string.filename_key));
            EditTextPreference filenamePrefix = (EditTextPreference) findPreference(getString(R.string.fileprefix_key));
            dirChooser = (FolderChooser) findPreference(getString(R.string.savelocation_key));
            floatingControl = (CheckBoxPreference) findPreference(getString(R.string.preference_floating_control_key));
            CheckBoxPreference touchPointer = (CheckBoxPreference) findPreference("touch_pointer");
            //Set previously chosen directory as initial directory
            dirChooser.setCurrentDir(getValue(getString(R.string.savelocation_key), defaultSaveLoc));

            ListPreference theme = (ListPreference) findPreference(getString(R.string.preference_theme_key));
            theme.setSummary(theme.getEntry());

            //Set the summary of preferences dynamically with user choice or default if no user choice is made
            updateScreenAspectRatio();
            updateResolution(res);
            fps.setSummary(getValue(getString(R.string.fps_key), "30"));
            float bps = bitsToMb(Integer.parseInt(getValue(getString(R.string.bitrate_key), "7130317")));
            bitrate.setSummary(bps + " Mbps");
            dirChooser.setSummary(getValue(getString(R.string.savelocation_key), defaultSaveLoc));
            filenameFormat.setSummary(getFileSaveFormat());
            filenamePrefix.setSummary(getValue(getString(R.string.fileprefix_key), "recording"));

            //If record audio checkbox is checked, check for record audio permission
            if (recaudio.isChecked())
                requestAudioPermission();

            //If floating controls is checked, check for system windows permission
            if (floatingControl.isChecked())
                requestSystemWindowsPermission();

            //set callback for directory change
            dirChooser.setOnDirectoryClickedListerner(this);
        }

        private void updateResolution(ListPreference pref) {
            pref.setSummary(getValue(getString(R.string.res_key), getNativeRes()));
        }

        private String getNativeRes() {
            DisplayMetrics metrics = getRealDisplayMetrics();
            return getScreenWidth(metrics) + "x" + getScreenHeight(metrics);
        }

        private void updateScreenAspectRatio() {
            Const.ASPECT_RATIO aspect_ratio = getAspectRatio();
            Log.d(Const.TAG, "Aspect ratio: " + aspect_ratio);
            CharSequence[] entriesValues = getResolutionEntriesValues(aspect_ratio);
            res.setEntries(entriesValues);
            res.setEntryValues(entriesValues);
        }

        private CharSequence[] getResolutionEntriesValues(Const.ASPECT_RATIO aspectRatio) {

            ArrayList<String> entries;
            switch (aspectRatio) {
                case AR16_9:
                    entries = buildEntries(R.array.resolutionsArray_16_9);
                    break;
                case AR18_9:
                    entries = buildEntries(R.array.resolutionValues_18_9);
                    break;
                default:
                    entries = buildEntries(R.array.resolutionsArray_16_9);
                    break;
            }

            String[] entriesArray = new String[entries.size()];
            return entries.toArray(entriesArray);
        }

        private ArrayList<String> buildEntries(int resID) {
            DisplayMetrics metrics = getRealDisplayMetrics();
            int width = getScreenWidth(metrics);
            int height = getScreenHeight(metrics);
            String nativeRes = width + "x" + height;
            ArrayList<String> entries = new ArrayList<>(Arrays.asList(getResources().getStringArray(resID)));
            Iterator<String> entriesIterator = entries.iterator();
            while (entriesIterator.hasNext()) {
                String entry = entriesIterator.next();
                String[] widthHeight = entry.split("x");
                if (width < Integer.parseInt(widthHeight[0]) || height < Integer.parseInt(widthHeight[1])) {
                    entriesIterator.remove();
                }
            }
            if (!entries.contains(nativeRes))
                entries.add(nativeRes);
            return entries;
        }

        private DisplayMetrics getRealDisplayMetrics(){
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager window = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
            window.getDefaultDisplay().getRealMetrics(metrics);
            return metrics;
        }

        private int getScreenWidth(DisplayMetrics metrics) {
            return metrics.widthPixels;
        }

        private int getScreenHeight(DisplayMetrics metrics) {
            return metrics.heightPixels;
        }

        private Const.ASPECT_RATIO getAspectRatio() {
            float screen_width = getScreenWidth(getRealDisplayMetrics());
            float screen_height = getScreenHeight(getRealDisplayMetrics());
            float aspectRatio;
            if (screen_width > screen_height) {
                aspectRatio = screen_width / screen_height;
            } else {
                aspectRatio = screen_height / screen_width;
            }
            return Const.ASPECT_RATIO.valueOf(aspectRatio);
        }

        private  void setPermissionListener() {
            if (getActivity() != null && getActivity() instanceof MainActivity) {
                Log.d("TETSTING","NOT_NULL");
                activity = (MainActivity) getActivity();
                activity.setPermissionResultListener(activity);
            }else{
                Log.d("TESTING>>>","");
            }
        }

        private String getValue(String key, String defVal) {
            return prefs.getString(key, defVal);
        }

        private float bitsToMb(float bps) {
            return bps / (1024 * 1024);
        }

        //Register for OnSharedPreferenceChangeListener when the fragment resumes
        @Override
        public void onResume() {
            super.onResume();
            getPreferenceScreen().getSharedPreferences()
                    .registerOnSharedPreferenceChangeListener(this);
        }

        //Unregister for OnSharedPreferenceChangeListener when the fragment pauses
        @Override
        public void onPause() {
            super.onPause();
            getPreferenceScreen().getSharedPreferences()
                    .unregisterOnSharedPreferenceChangeListener(this);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
        }

        //When user changes preferences, update the summary accordingly
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
            Preference pref = findPreference(s);
            if (pref == null) return;
            switch (pref.getTitleRes()) {
                case R.string.preference_resolution_title:
                    updateResolution((ListPreference) pref);
                    break;
                case R.string.preference_fps_title:
                    String fps = String.valueOf(getValue(getString(R.string.fps_key), "30"));
                    pref.setSummary(fps);
                    break;
                case R.string.preference_bit_title:
                    float bps = bitsToMb(Integer.parseInt(getValue(getString(R.string.bitrate_key), "7130317")));
                    pref.setSummary(bps + " Mbps");
                    break;
                case R.string.preference_filename_format_title:
                    pref.setSummary(getFileSaveFormat());
                    break;
                case R.string.preference_audio_record_title:
                    requestAudioPermission();
                    break;
                case R.string.preference_filename_prefix_title:
                    EditTextPreference etp = (EditTextPreference) pref;
                    etp.setSummary(etp.getText());
                    ListPreference filename = (ListPreference) findPreference(getString(R.string.filename_key));
                    filename.setSummary(getFileSaveFormat());
                    break;
                case R.string.preference_floating_control_title:
                    requestSystemWindowsPermission();
                    break;
                case R.string.preference_show_touch_title:
                    CheckBoxPreference showTouchCB = (CheckBoxPreference)pref;
                    if (showTouchCB.isChecked() && !hasPluginInstalled()){
                        showTouchCB.setChecked(false);
                        showDownloadAlert();
                    }
                    break;
                case R.string.preference_crash_reporting_title:
                    CheckBoxPreference crashReporting = (CheckBoxPreference)pref;
                    CheckBoxPreference anonymousStats = (CheckBoxPreference) findPreference(getString(R.string.preference_anonymous_statistics_key));
                    if(!crashReporting.isChecked())
                        anonymousStats.setChecked(false);
                    break;
                case R.string.preference_anonymous_statistics_title:
                    break;
                case R.string.preference_theme_title:
                    activity.recreate();
                    break;
            }
        }

        private void showDownloadAlert() {
            new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.alert_plugin_not_found_title)
                    .setMessage(R.string.alert_plugin_not_found_message)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            try {
                                getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.orpheusdroid.screencamplugin")));
                            } catch (android.content.ActivityNotFoundException e) { // if there is no Google Play on device
                                getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.orpheusdroid.screencamplugin")));
                            }
                        }
                    })
                    .setNeutralButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .create().show();
        }

        private boolean hasPluginInstalled(){
            PackageManager pm = getActivity().getPackageManager();
            try {
                pm.getPackageInfo("com.orpheusdroid.screencamplugin",PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
                Log.d(Const.TAG, "Plugin not installed");
                return false;
            }
            return true;
        }

        public String getFileSaveFormat() {
            String filename = prefs.getString(getString(R.string.filename_key), "yyyyMMdd_hhmmss");
            String prefix = prefs.getString(getString(R.string.fileprefix_key), "recording");
            return prefix + "_" + filename;
        }

        public void requestAudioPermission() {
            if (activity != null) {
                Log.d("TESTING","finalyyyy");
                activity.requestPermissionAudio();
            }else{
                Log.d("TESTING","null");

            }
        }

        private void requestSystemWindowsPermission() {
            if (activity != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                activity.requestSystemWindowsPermission();
            } else {
                Log.d(Const.TAG, "API is < 23");
            }
        }

        private void showSnackbar() {
            Snackbar.make(getActivity().findViewById(R.id.fab), R.string.snackbar_storage_permission_message,
                    Snackbar.LENGTH_INDEFINITE).setAction(R.string.snackbar_storage_permission_action_enable,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (activity != null){
                                activity.requestPermissionStorage();
                            }
                        }
                    }).show();
        }

        private void showPermissionDeniedDialog(){
            new AlertDialog.Builder(activity)
                    .setTitle(R.string.alert_permission_denied_title)
                    .setMessage(R.string.alert_permission_denied_message)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (activity != null){
                                activity.requestPermissionStorage();
                            }
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            showSnackbar();
                        }
                    })
                    .setIconAttribute(android.R.attr.alertDialogIcon)
                    .setCancelable(false)
                    .create().show();
        }

        @Override
        public void onPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
            switch (requestCode) {
                case Const.EXTDIR_REQUEST_CODE:
                    if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_DENIED)) {
                        Log.d(Const.TAG, "Storage permission denied. Requesting again");
                        dirChooser.setEnabled(false);
                        showPermissionDeniedDialog();
                    } else if((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
                        dirChooser.setEnabled(true);
                    }
                    return;
                case Const.AUDIO_REQUEST_CODE:
                    if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                        Log.d(Const.TAG, "Record audio permission granted.");
                        recaudio.setChecked(true);
                    } else {
                        Log.d(Const.TAG, "Record audio permission denied");
                        recaudio.setChecked(false);
                    }
                    return;
                case Const.SYSTEM_WINDOWS_CODE:
                    if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                        Log.d(Const.TAG, "System Windows permission granted");
                        floatingControl.setChecked(true);
                    } else {
                        Log.d(Const.TAG, "System Windows permission denied");
                        floatingControl.setChecked(false);
                    }
                default:
                    Log.d(Const.TAG, "Unknown permission request with request code: " + requestCode);
            }
        }

        @Override
        public void onDirectorySelected() {
            Log.d(Const.TAG, "In settings fragment");
            if (getActivity() != null && getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).onDirectoryChanged();
            }
        }
    }

}
vijai1996 commented 6 years ago

You mean say, you are trying to use the code in your app and its not working?

bharathnr21 commented 6 years ago

Yes, i am using your code for one of our internal project. I am trying to load the SettingPreferenceFragment in SettingsActivity. But i am activity has null.

private void setPermissionListener() { if (getActivity() != null && getActivity() instanceof MainActivity) { Log.d("TETSTING","NOT_NULL"); activity = (MainActivity) getActivity(); activity.setPermissionResultListener(activity); }else{ Log.d("TESTING>>>",""); } }

vijai1996 commented 6 years ago

Well, I cannot help much without seeing your code but your best bet would be to ask in stackoverflow as the question to extensive is not related to this repository.

Also a point to note, If you are using any code you must comply with the opensource license.

Closing this issue for now.