PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label android-intent. Show all posts
Showing posts with label android-intent. Show all posts

Monday, November 7, 2022

[FIXED] How to exclude your own app from the Share menu?

 November 07, 2022     android, android-intent, menu, share     No comments   

Issue

The app has an intent filter to allow it to appear in the share menu in other applications via ACTION_SEND intents. The app itself also has a share menu using ACTION_SEND and createChooser(), and my app appears in the list. Since they are already in my app it seems strange to have them be able to share back to itself.

Is there a way for my app not to appear in the list if it's being called from my app?


Solution

Is there a way for my app not to appear in the list if it's being called from my app?

Not via createChooser(). You can create your own chooser-like dialog via PackageManager and queryIntentActivities() and filter yourself out that way, though.



Answered By - CommonsWare
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 6, 2022

[FIXED] How can I add a VCard to contacts with Xamarin(Android)?

 November 06, 2022     android-intent, c#, contacts, xamarin.forms     No comments   

Issue

1.With this method I can transfer a Vcard to the contacts, but this method is out of date and I can't find a way to add VCard / website to Contact / website. How to write the current method to add a Vcard to the contacts?

public void SaveContacts(
    string name, string number, string email, string
    company, string jobtitle, string postal, string website)
{
    var activity = Forms.Context as Activity;
    var intent = new Intent(Intent.ActionInsert);
    intent.SetType(ContactsContract.Contacts.ContentType);
    intent.PutExtra(ContactsContract.Intents.Insert.Name, name);
    intent.PutExtra(ContactsContract.Intents.Insert.Phone, number);
    intent.PutExtra(ContactsContract.Intents.Insert.Email, email);
    intent.PutExtra(ContactsContract.Intents.Insert.Company, company);
    intent.PutExtra(ContactsContract.Intents.Insert.JobTitle, jobtitle);
    intent.PutExtra(ContactsContract.Intents.Insert.Postal, postal);
    intent.PutExtra(ContactsContract.Intents.Insert.Notes, website);

    activity.StartActivity(intent);
    Toast.MakeText(activity, "ContactSaved", ToastLength.Short).Show();
}

Solution

You can refer to the following code,and it could add a contact with multiple phone numbers in android. It works on my side.

 public class MainActivity : AppCompatActivity
    {
        public  string TAG
        {
            get
            {
                return "MainActivity";
            }
        }
        static readonly int REQUEST_CONTACTS = 1;

        static string[] PERMISSIONS_CONTACT = {
            Manifest.Permission.ReadContacts,
            Manifest.Permission.WriteContacts
        };

        Button button;

        View  layout;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            layout = FindViewById(Resource.Id.root_layout);

        }

        public void NewContact(ref List<ContentProviderOperation> ops, string displayName, string Number1, string Number2, string Number3, string Number4)
        {
            ContentProviderOperation.Builder builder =
                ContentProviderOperation.NewInsert(ContactsContract.RawContacts.ContentUri);
            builder.WithValue(ContactsContract.RawContacts.InterfaceConsts.AccountType, null);
            builder.WithValue(ContactsContract.RawContacts.InterfaceConsts.AccountName, null);
            ops.Add(builder.Build());

            //Name  
            builder = ContentProviderOperation.NewInsert(ContactsContract.Data.ContentUri);
            builder.WithValueBackReference(ContactsContract.Data.InterfaceConsts.RawContactId, 0);
            builder.WithValue(ContactsContract.Data.InterfaceConsts.Mimetype,
                              ContactsContract.CommonDataKinds.StructuredName.ContentItemType);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.DisplayName, displayName);
            //builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.GivenName, firstName);  
            ops.Add(builder.Build());

            //Number1  
            builder = ContentProviderOperation.NewInsert(ContactsContract.Data.ContentUri);
            builder.WithValueBackReference(ContactsContract.Data.InterfaceConsts.RawContactId, 0);
            builder.WithValue(ContactsContract.Data.InterfaceConsts.Mimetype,
                              ContactsContract.CommonDataKinds.Phone.ContentItemType);
            builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, Number1);
            builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type,
                              ContactsContract.CommonDataKinds.Phone.InterfaceConsts.TypeCustom);
            builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Data2, (int)PhoneDataKind.Mobile);

            ops.Add(builder.Build());
            //Number2  
            if (!string.IsNullOrEmpty(Number2))
            {
                builder = ContentProviderOperation.NewInsert(ContactsContract.Data.ContentUri);
                builder.WithValueBackReference(ContactsContract.Data.InterfaceConsts.RawContactId, 0);
                builder.WithValue(ContactsContract.Data.InterfaceConsts.Mimetype,
                                  ContactsContract.CommonDataKinds.Phone.ContentItemType);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, Number2);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type,
                                  ContactsContract.CommonDataKinds.Phone.InterfaceConsts.TypeCustom);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Data2, (int)PhoneDataKind.Mobile);
                ops.Add(builder.Build());
            }

            if (!string.IsNullOrEmpty(Number3))
            {
                builder = ContentProviderOperation.NewInsert(ContactsContract.Data.ContentUri);
                builder.WithValueBackReference(ContactsContract.Data.InterfaceConsts.RawContactId, 0);
                builder.WithValue(ContactsContract.Data.InterfaceConsts.Mimetype,
                                  ContactsContract.CommonDataKinds.Phone.ContentItemType);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, Number3);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type,
                                  ContactsContract.CommonDataKinds.Phone.InterfaceConsts.TypeCustom);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Data2, (int)PhoneDataKind.Mobile);
                ops.Add(builder.Build());
            }

            if (!string.IsNullOrEmpty(Number4))
            {
                builder = ContentProviderOperation.NewInsert(ContactsContract.Data.ContentUri);
                builder.WithValueBackReference(ContactsContract.Data.InterfaceConsts.RawContactId, 0);
                builder.WithValue(ContactsContract.Data.InterfaceConsts.Mimetype,
                                  ContactsContract.CommonDataKinds.Phone.ContentItemType);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, Number4);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type,
                                  ContactsContract.CommonDataKinds.Phone.InterfaceConsts.TypeCustom);
                builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Data2, (int)PhoneDataKind.Mobile);
                ops.Add(builder.Build());
            }

        }

        /*
        public void SaveContacts(string filename)
        {
            var documentsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
            var filePath = Path.Combine(documentsPath.AbsolutePath, filename);
            var fileContent = File.ReadAllLines(filePath);

            List<ContentProviderOperation> ops = new List<ContentProviderOperation>();

            foreach (var strLine in fileContent)
            {
                if (string.IsNullOrEmpty(strLine))
                    continue;
                var array = strLine.Split(new string[] { "\t", ":" }, StringSplitOptions.RemoveEmptyEntries);

               // NewContact(...);

                //Add the new contact  
                ContentProviderResult[] res;
                res = ContentResolver.ApplyBatch(ContactsContract.Authority, ops);
                ops.Clear();
            }
        }

        */
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
             if (requestCode == REQUEST_CONTACTS)
            {
                Log.Info(TAG, "Received response for contact permissions request.");

                // We have requested multiple permissions for contacts, so all of them need to be
                // checked.
                if (PermissionUtil.VerifyPermissions(grantResults))
                {
                    // All required permissions have been granted, display contacts fragment.
                    Snackbar.Make(layout, Resource.String.permission_available_contacts, Snackbar.LengthShort).Show();

                    // save contact
                    saveContact();
                }
                else
                {
                    Log.Info(TAG, "Contacts permissions were NOT granted.");
                    Snackbar.Make(layout, Resource.String.permissions_not_granted, Snackbar.LengthShort).Show();
                }

            }
            else
            {
                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }


        [Export]
        public void SaveContacts(View v)
        {
            Log.Info(TAG, "Show contacts button pressed. Checking permissions.");

            // Verify that all required contact permissions have been granted.
            if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadContacts) != (int)Permission.Granted
                || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.WriteContacts) != (int)Permission.Granted)
            {
                // Contacts permissions have not been granted.
                Log.Info(TAG, "Contact permissions has NOT been granted. Requesting permissions.");
                RequestContactsPermissions();
            }
            else
            {
                // Contact permissions have been granted. Show the contacts fragment.
                Log.Info(TAG, "Contact permissions have already been granted. Displaying contact details.");

                //Add the new contact

                saveContact();
            }
        }


        void RequestContactsPermissions()
        {
            if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.ReadContacts)
                || ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.WriteContacts))
            {

                // Provide an additional rationale to the user if the permission was not granted
                // and the user would benefit from additional context for the use of the permission.
                // For example, if the request has been denied previously.
                Log.Info(TAG, "Displaying contacts permission rationale to provide additional context.");

                // Display a SnackBar with an explanation and a button to trigger the request.
                Snackbar.Make(layout, Resource.String.permission_contacts_rationale,
                    Snackbar.LengthIndefinite).SetAction(Resource.String.ok, new Action<View>(delegate (View obj) {
                        ActivityCompat.RequestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
                    })).Show();

            }
            else
            {
                // Contact permissions have not been granted yet. Request them directly.
                ActivityCompat.RequestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
            }
        }


        public void saveContact() {
            List<ContentProviderOperation> ops = new List<ContentProviderOperation>();
            NewContact(ref ops, "test", "1234", "2234", "3234", "4234");

            //Add the new contact
            ContentProviderResult[] res;
            try
            {
                res = ContentResolver.ApplyBatch(ContactsContract.Authority, ops);
                ops.Clear();//Add this line   
                Toast.MakeText(this, "contact saved !", ToastLength.Short).Show();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("**************-----------> : " + e.Message);
                Toast.MakeText(this, "contact not saved_message !", ToastLength.Long).Show();
            }
        }
    }

class PermissionUtil

public abstract  class PermissionUtil
{
    public static bool VerifyPermissions(Permission[] grantResults)
    {
        // At least one result must be checked.
        if (grantResults.Length < 1)
            return false;

        // Verify that each required permission has been granted, otherwise return false.
        foreach (Permission result in grantResults)
        {
            if (result != Permission.Granted)
            {
                return false;
            }
        }
        return true;
    }
}

layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     android:id="@+id/root_layout"
    >

    <Button
        android:id="@+id/saveBtn"
        android:onClick="SaveContacts"
        android:text="save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Note:

1.Rembember to add the following permissions in your manifest:

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

And an app that targets Android 6.0 must always perform a runtime permission check.

For more details, check: https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/permissions?tabs=windows

2.add reference Mono.Android.Export;

3.You can refer official sample: https://github.com/xamarin/monodroid-samples/tree/master/android-m/RuntimePermissions .



Answered By - Jessie Zhang -MSFT
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to press Save Contact Button Programmatically

 November 06, 2022     android, android-intent, contacts, java     No comments   

Issue

I Have code which takes my to the save contact screen, fills the details i need, however i need it to now just automatically press save contact too. Does anyone know how? Or if it is even possible.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
        contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

        contactIntent
                .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
                .putExtra(ContactsContract.Intents.Insert.PHONE, "123456789");

        startActivityForResult(contactIntent, 1);

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

        if (requestCode == 1)
        {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

Solution

You can use button.performClick(). If you need demonstrate that button was clicked you can use my sample:

class MainActivity : AppCompatActivity() {
    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.button)
        // this code demonstrate success work
        button.setOnClickListener {
            Toast.makeText(this, "event occurred", Toast.LENGTH_LONG).show()
        }

        // create event with your params
        var ev = MotionEvent.obtain(1L, System.currentTimeMillis(),0, button.x, button.y, 0)


        val b2 = findViewById<Button>(R.id.button2)
        b2.setOnClickListener {
            button.onTouchEvent(ev)
        }
    }
}


Answered By - IlyaFromRussia
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 26, 2022

[FIXED] How to add an option to share to Instagram Stories?

 October 26, 2022     android, android-intent, instagram     No comments   

Issue

Background
In my Android App, users can share generated images to other apps. It's working nicely using the ACTION_SEND Intent.
Many users have asked why they can't share to Instagram stories directly.

Initially I thought Instagram doesn't support receiving Intents for stories (correct to some extent). I searched for it today, and according to this documentation, to share to Instagram Stories, a separate intent com.instagram.share.ADD_TO_STORY has to be used. I tried it, and it works fine.

The problem:
How do I keep both the options available?

I thought about it a lot, and came up with the following options:

1) Have two separate buttons. It will work, but it will look/feel bad.

2) Have my app accept ACTION_SEND intent, name it as Share to Instagram Story, and redirect the intent to the com.instagram.share.ADD_TO_STORY intent. In principle, make a proxy intent.
It will work, and look/feel great, but I don't know if its allowed (legal, etc) and can I disable the intent if the user doesn't have Instagram installed.

3) Add the 'com.instagram.share.ADD_TO_STORY' to the app chooser launched by ACTION_SEND. This would be ideal, but I don't know how to do it.


Solution

If you want to add multiple actions to Intent and create a chooser look at this example:

Intent viewIntent = new Intent(Intent.ACTION_VIEW);
Intent editIntent = new Intent(Intent.ACTION_EDIT);
viewIntent.setDataAndType(uri, type);
editIntent.setDataAndType(uri, type);
Intent chooserIntent = Intent.createChooser(editIntent, "Open in...");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { viewIntent });
startActivity(chooserIntent);

UPDATE: Here is good solution to your answer. How to make an intent with multiple actions



Answered By - Nazarii Moshenskiy
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 28, 2022

[FIXED] How to scroll among images viewed via intent in android

 July 28, 2022     android, android-intent, image, photo, scroll     No comments   

Issue

I have created a function to view images in a single view using following Intent.

Intent intent = new Intent();
                        intent.setAction(android.content.Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(temp.getPath())), "image/*");
                        startActivity(intent);

It opens a default gallery app to view the images. However I cannot go to next image by sliding the screen as it normally happens in simple gallery app. How could I do it? The scenario is I have a grid view displaying thumbnails of pics. Now when somebody click on it, it is opened via intent and displayed in full screen but to see next image, user has to go back and then click the next image. What would be the procedure to switch images when a person slide the screen horizontally.


Solution

I got the answer. Actually, I was not able to swipe the images to see next one because the default gallery app doesn't knew that more image exists in that path. So I notified the media resolver using broadcast intent and then I was able to swipe images.



Answered By - waterbyte
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 12, 2022

[FIXED] How to hide keyboard automatically after sending e-mail using emailIntent

 July 12, 2022     android, android-intent, keyboard, message     No comments   

Issue

There is a page where the user can send e-mail, sms or call its guests when needed. The problem is that when the user sends e-mail to its guest, the keyboard doesn't hide. Even-though I have a small problem solving the issue, It still seems hard to find alike post to solve it. I'll be also making screenshots and placing them in here.

enter image description here enter image description here enter image description here enter image description here

As you can see, the keyboard doesn't hide after sending mail.


Solution

Intent sendIntent = new Intent(Intent.ACTION_SEND);
                            sendIntent.setType("text/plain");
                            sendIntent.putExtra(Intent.EXTRA_EMAIL,
                                    new String[] { **EmailAddress** });
                            startActivityForResult(sendIntent, 1);




   @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) activity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(**AnyViewOfScreen**.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 300);
    }


Answered By - Vishal
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing