How to set dialog on the top screen without activity or call from service - dialog

For this question i want to share my task, very burnout task and new experiment for me,
I have more task And finnally code for test :
fun showAlertTest(){
val builder = AlertDialog.Builder(this)
builder.setTitle("This is Alert Dialog")
builder.setMessage("Bottom Alert dialog")
// set the neutral button to do some actions
// set the neutral button to do some actions
builder.setNeutralButton(
"DISMISS"
) { dialog, which ->
Toast.makeText(this, "Alert Dialog Dismissed", Toast.LENGTH_SHORT).show()
}
// set the positive button to do some actions
// set the positive button to do some actions
builder.setPositiveButton(
"OKAY"
) { dialog, which -> Toast.makeText(this, "OKAY", Toast.LENGTH_SHORT).show() }
// set the negative button to do some actions
// set the negative button to do some actions
builder.setNegativeButton(
"CANCEL"
) { dialog, which ->
Toast.makeText(this, "CANCEL", Toast.LENGTH_SHORT).show()
}
// show the alert dialog
// show the alert dialog
val alertDialog = builder.create()
// Set to TYPE_SYSTEM_ALERT so that the Service can display it
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alertDialog.window!!.setType(WindowManager.LayoutParams.TYPE_TOAST);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
alertDialog.window!!.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
{
alertDialog.window!!.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
alertDialog.show()
}
NB : thanks a lot for this answer https://stackoverflow.com/a/48181241/8636506

Related

how show system lock(i.e. Pattern/Fingerprint) on activity started from Broadcast Receiver currently on top of Lock screen android 11

Here is my code fore starting lock screen. onActivityResult giving Result-Cancelled every time can someone help me out ,
private fun checkPhoneScreenLocked(context: Context) {
val myKM = context.getSystemService(KEYGUARD_SERVICE) as KeyguardManager
if (myKM.isKeyguardLocked) {
// Phone is locked
val credentialsIntent = myKM.createConfirmDeviceCredentialIntent(
"Password required",
"please enter your pattern to receive your token"
)
if (credentialsIntent != null) {
startActivityForResult(credentialsIntent, CREDENTIALS_RESULT)
}
}else{
// Phone is not locked
}
}

Capture Dialog Box Edit Text Changes in Fragment

I’m in Android Studio version Chipmunk with one patch. I’m writing in Kotlin, a language I find is just beautiful. I have a dialog box over a fragment where I want to capture the changes in the edit text box as they happen. I’ve tried with straightforward code found here in Stack Overflow but I think the fragment can’t view the dialog box.
Following is code used:
private fun dlgFind() {
try {
//val sTxt: EditText = findViewById(R.id.txtStock)
val sTxt = binding.txtMeds
val spannable: Spannable = SpannableString(sTxt.text.toString())
sTxt.setText(spannable.toString()) // clears highlighted text
val dialog = Dialog(requireContext(), R.style.RoundedCornersDialogFind)
dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) // makes frag text readable
dialog.setContentView(R.layout.dlg_find)
// tried to max dialog window to full width of screen
//dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val btnFind = dialog.findViewById(R.id.btnGo) as ImageButton
val txtFind = dialog.findViewById(R.id.editFind) as EditText
txtFind.isFocusableInTouchMode = true
txtFind.isFocusable = true
//txtFind.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
txtFind.requestFocus()
txtFind.postDelayed({
txtFind.requestFocus()
val imm = context?.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(txtFind, InputMethodManager.SHOW_IMPLICIT)
}, 1)
btnFind.setOnClickListener { dialog.dismiss()
gsFindBoxTxt = txtFind.text.toString()
sTxt.requestFocus()
//sTxt.setText(spannable.toString()) // clears highlighted text
findWithDlg() // method finds strings
}
//dialog.setOnCancelListener { editHours() }
dialog.window?.setGravity(Gravity.BOTTOM)
dialog.show()
} catch (e: Exception) {
val methodName = object {}.javaClass.enclosingMethod?.name
Toast.makeText(context, methodName.toString(), Toast.LENGTH_LONG).show()
}
}
Attempt to read from dialog box in fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
try {
val sEditTxt = view.findViewById<EditText>(R.id.editFind)
sEditTxt?.doOnTextChanged { _, _, _, _ ->
Toast.makeText(context, "!", Toast.LENGTH_LONG).show() }
if (sEditTxt?.text != null) {
sEditTxt.doAfterTextChanged {
Toast.makeText(context, "!", Toast.LENGTH_LONG).show()
findWithDlg()
}
}
} catch (e: Exception) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show()
}
Note I have tried boilerplate TextWatcher code too and I can't return view in onCreate because I'm using binding throughout the fragment. The return in onCreate is to the binding.root. And even in onDestroyView the last line is _binding = null. Maybe remove all binding and revert to using views?
I've also tried these in the dialog method (function) to no avail yet...
Yes! I figured out how to listen to the text changes. I set following in the dialog method:
dialog.setOnShowListener { txtFind.doOnTextChanged { _, _, _, _ ->
Toast.makeText(context, "Text Change", Toast.LENGTH_LONG).show()
}
}

I have a click button that sets the wallpaper from URL both for lock and home screen but it does not work for lockScreen in API level 28 or lower

I am tring to set an image from URL as wallaper for both home screen and lock screen.it is not working for lock screen for API level 28 or lower but works for home screen.
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
var input: InputStream? = null
try {
input = URL(intent).openStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val wallpaperManager = WallpaperManager.getInstance(applicationContext)
wallpaperManager.setStream(
input, null, true,
WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM
)
Toast.makeText(this, "Wallpaper set successfully!", Toast.LENGTH_SHORT)
.show()
}
} catch (e: Exception) {
e.printStackTrace()
}

How to get both Microphone and Camera permissions with webview

I am getting error "Either grant() or deny() has been already called" when I am trying to access a page in WebView that requires both Microphone and Camera access.
That's my on onPermissionRequest but for some reason if both of them are requested in the same time the app crashes but with only one request seems to work fine.
override fun onPermissionRequest(permissionRequest: PermissionRequest?) {
Log.d(TAG, "onJSPermissionRequest")
val mPermissionRequest: PermissionRequest? = permissionRequest
for (request in permissionRequest?.resources!!){
if (request == PermissionRequest.RESOURCE_VIDEO_CAPTURE){
val alertDialogBuilder = AlertDialog.Builder(mContext)
.setTitle("Allow Permission to Camera access!")
.setPositiveButton("Allow") { dialog, which ->
dialog.dismiss()
mPermissionRequest?.grant(arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE))
}
.setNegativeButton("Deny") { dialog, which ->
dialog.dismiss()
mPermissionRequest?.deny()
}
val alertDialog = alertDialogBuilder.create()
alertDialog.show()
}
if(request == PermissionRequest.RESOURCE_AUDIO_CAPTURE){
val alertDialogBuilder = AlertDialog.Builder(mContext)
.setTitle("Allow Permission to Microphone access!")
.setPositiveButton("Allow") { dialog, which ->
dialog.dismiss()
mPermissionRequest?.grant(arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE))
}
.setNegativeButton("Deny") { dialog, which ->
dialog.dismiss()
mPermissionRequest?.deny()
}
val alertDialog = alertDialogBuilder.create()
alertDialog.show()
}
}
}
override fun onPermissionRequestCanceled(request: PermissionRequest?) {
super.onPermissionRequestCanceled(request)
Toast.makeText(mContext,"Permission Denied",Toast.LENGTH_SHORT).show()
}
}
}
I know the issue is because I asking for grant twice (removing the grant command in one of the cases solves the crash but now giving permissions) but the resources are different for both requests..

OnInitMenuPopup does not init correctly when called from a toolbar button that was a POPUP menu in the App main menu bar

To make a long history short, imagine my main menu is a CMFCMenuBar which menu is defined by:
IDR_MAINFRAME MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "New", ID_FILE_NEW
MENUITEM "Open", ID_FILE_OPEN
MENUITEM "Save", ID_FILE_SAVE
POPUP "Save As"
BEGIN
MENUITEM "Format XXX", ID_FILE_SAVEAS_XXX
MENUITEM SEPARATOR
MENUITEM "Format YYY", ID_FILE_SAVEAS_YYY
MENUITEM SEPARATOR
MENUITEM "Format ZZZ", ID_FILE_SAVEAS_ZZZ
MENUITEM "Format WWW", ID_FILE_SAVEAS_WWW
END
MENUITEM "Close", ID_FILE_CLOSE
END
POPUP "&Object"
BEGIN
POPUP "Create object"
BEGIN
MENUITEM "Create object...", ID_CREATE_OBJECT
MENUITEM "Create object as...", ID_CREATE_OBJECTAS
END
POPUP "Save object"
BEGIN
MENUITEM "Save object...", ID_SAVE_AS_XXX
MENUITEM "Save object copy", ID_SAVE_OBJECT_COPY
END
END
MENUITEM "Delete", ID_DELETE_OBJECT
END
END
As POPUP menus have no ID (all them have a value of -1), to know on what menu I am doing the initialization, I followed the approach on https://stackoverflow.com/a/3910405/383779 and implemented functions like
bool CMainFrame::IsFileMenu(CMenu* pPopupMenu) const
{
if(!pPopupMenu);
return false;
return (pPopupMenu->GetMenuItemCount() > 0) && (pPopupMenu->GetMenuItemID(0) == ID_FILE_NEW);
}
bool CMainFrame::IsObjectMenu(CMenu* pPopupMenu) const
{
if(!pPopupMenu);
return false;
return (pPopupMenu->GetMenuItemCount() > 0) && (pPopupMenu->GetMenuItemID(2) == ID_DELETE_OBJECT);
}
The Menu initialization is like:
void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
if(!license.supports("SaveAsFile"))
{
if(IsFileMenu())
{
//code to find ID_FILE_SAVEAS_XXX parent menu ("Save As"), then recursively delete all its descendants and itself
}
if(IsObjectMenu())
{
for(int i = 0; i < pPopupMenu->GetMenuItemCount();i++)
{
MENUITEMINFO MenuItemInfo;
memset(&MenuItemInfo, 0, sizeof(MENUITEMINFO));
MenuItemInfo.cbSize = sizeof (MENUITEMINFO); // must fill up this field
MenuItemInfo.fMask = MIIM_SUBMENU;
if (!pPopupMenu->GetMenuItemInfo(i, &MenuItemInfo, TRUE))
continue;
CMenu* SubMenu = pPopupMenu->GetSubMenu(i);
if (SubMenu != NULL)
{
memset(&MenuItemInfo, 0, sizeof(MENUITEMINFO));
MenuItemInfo.cbSize = sizeof (MENUITEMINFO);
MenuItemInfo.fMask = MIIM_ID | MIIM_TYPE;
for(int j=0; j<SubMenu->GetMenuItemCount() ;j++ )
{
SubMenu->GetMenuItemInfo(j, &MenuItemInfo, TRUE);
if (MenuItemInfo.wID == ID_CREATE_OBJECTAS)
{
for (int i=0; i<m_custom_objects.GetSize(); i++)
pPopup->AppendMenu(MF_STRING | MF_ENABLED, WM_MENU_CUSTOM_OBJECTS_BEGIN + i, (LPCTSTR) m_custom_objects[i].GetName() );
found= true;
break;
}
}
if(found)
break;
}
}
}
}
__super::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
}
Notice the ID_FILE_SAVEAS_XXX MENUITEM identifer is repeated! As I don't'want to delete the "Save Object" POPUP when the the license supporting "SaveAsFile" is absent, so it is an absolute need to identify what menu is now being processed.
Now the user has created a toolbar by using the MFC Customize dialog, then he dragged the "Create Object" POPUP to the new toolbar. When he clicks this new button of the toolbar, he sees the "Create object" and "Create object as" option, but not the custom objects have not been appended because to the IsObjectMenu() condition was not satisfied. The behaviour was completely different when he came from the main menu; the appending has been done!
How can I make the code in a way that the Appending of custom objects is done when the user clicks the button of the toolbar?
I am not proud of my own code, but I solved it by separating the code of "Object" from "Create Object" menu.
bool CMainFrame::IsCreateObjectMenu(CMenu* pPopupMenu) const
{
if(!pPopupMenu);
return false;
return (pPopupMenu->GetMenuItemCount() > 0) && (pPopupMenu->GetMenuItemID(0) == ID_CREATE_OBJECT);
}
void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
if(!license.supports("SaveAsFile"))
{
if(IsFileMenu())
{
//code to find ID_FILE_SAVEAS_XXX parent menu ("Save As"), then recursively delete all its descendants and itself
}
if(IsObjectMenu())
{
// Do things
}
if(IsCreateObjectMenu())
{
for (int i=0; i<m_custom_objects.GetSize(); i++)
pPopupMenu->AppendMenu(MF_STRING | MF_ENABLED, WM_MENU_CUSTOM_OBJECTS_BEGIN + i, (LPCTSTR) m_custom_objects[i].GetName());
}
}
__super::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
}

Resources