Tuesday 30 November 2021

Delete phone call logs programmatically

 
Here we are going to explain how we can delete all phone call logs programmatically


Include the READ_CALL_LOG and WRITE_CALL_LOG permissions in your manifest file,
 
  <uses-permission android:name="android.permission.READ_CALL_LOG"/>
  <uses-permission android:name="android.permission.WRITE_CALL_LOG"/>



Here is the function to delete all the phone calls, specify a  TYPE for the calls so that it gets removed,

private void deletePhoneCallLogs() {
    Cursor cursor = getContext().getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(CallLog.Calls._ID));
        Uri deleteUri = ContentUris.withAppendedId(CallLog.Calls.CONTENT_URI, id);
        Log.d("PhoneCall","My delete PhoneCall"+deleteUri);
        getContext().getContentResolver().delete(CallLog.Calls.CONTENT_URI , "type="+CallLog.Calls.TYPE , null);        }
    cursor.close();
}



Here is the type of the call (incoming, outgoing or missed).
INCOMING_TYPE
OUTGOING_TYPE
MISSED_TYPE
VOICEMAIL_TYPE
REJECTED_TYPE
BLOCKED_TYPE
ANSWERED_EXTERNALLY_TYPE



For delete the missed calls here is the code,

getContentResolver().delete(CallLog.CONTENT_URI , "type="+CallLog.Calls.MISSED_TYPE , null);




You can get more information about Call Types from here  https://developer.android.com/reference/android/provider/CallLog.Calls#TYPE




Monday 29 November 2021

Context on Android

 Here we are going to explain what's exactly is a Context class in Android and what is it used for?

As the name suggests, it's the context of the current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).
Typical uses of context:

  • Creating new objects : Creating new views, adapters, listeners:
 TextView tv = new TextView(getContext());
 ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);

  • Accessing standard common resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
 context.getSystemService(LAYOUT_INFLATER_SERVICE)
 getApplicationContext().getSharedPreferences(*name*, *mode*);


  • Accessing components implicitly: Regarding content providers, broadcasts, intent
 getApplicationContext().getContentResolver().query(uri, ...);


You can read more from the Developer Site, From there you can understand it more clearly.



How to get screen dimensions as pixels in Android

Here we are going to explain how we can get screen Width and screen Height of a device.


If you want the display dimensions in pixels you can use
getSize():

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;


If you're not in an Activity you can get the default Display via WINDOW_SERVICE:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();


If you are in a fragment and want to accomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).

Before getSize() was introduced (in API level 13), you could use the getWidth() and getHeight() methods that are now deprecated:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated




Another way is: DisplayMetrics

A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics() members, initialize an object like this:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Log.d("ApplicationName", "Display width in px is " + metrics.widthPixels);



Unique device ID of Android

 On every android device Settings.Secure.ANDROID_ID will returns the Android ID as an unique for each user 64-bit hex string. This id should be unique to devices, but how it is set depends on the implementation of the device manufacturer.

Here is the code how we can get this ID,


import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);


The Android Id may change on factory reset of the phone and the user is also able to change it on rooted phones. But if you need an id to identify your user it should be fine.


Also read Best practices for unique identifiers: https://developer.android.com/training/articles/user-data-ids





Notifications in Android application

In android, Notification is a message which is used to alert the users about some events that happening in our app.

In android, we can alert the users about our app notifications in different forms like a flash the LED or make sounds or display an icon in the status bar, etc. Generally, the android Notifications will be displayed outside of our app’s normal UI and alert the users without interrupting their current activities.


Here we are going to use NotificationCompat class to implement notification in our android application. The NotificationCompat class supports different types of notification views, such as normal view, big view and it provides the best support for a wide range of platforms. 


To create a notification, we need to specify the UI content and required actions with a
NotificationCompat.Builder object. To display an icon, title and detailed text of notification we need to set the following properties in Builder object.
 
setSmallIcon() : To set the small icon for our notification.
setContentTitle() : To set the title of our notification.
setContentText() : To set the detailed text to display in notification.

The above-mentioned properties are necessary to display a notification and we can set a different type of properties to our notification like
setStyle, setSound, setLights, setLargeIcon, etc. based on our requirements using Builder object.
 

Here is the example of creating a notification using
NotificationCompat.Build object and setting the notification properties.


NotificationCompat.Builder nBuilder =  new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentTitle("Notification Title")
                .setContentText("Hi, This will be the notification content");




If we assign an action to the notification, it will allow users to go directly from the notification to an activity of our app. We can also add buttons to the notification to perform additional actions such as hang up the call or responding immediately to a text message; this feature is available as of Android 4.1.

In android, we can define an action inside of notification by using
PendingIntent object which contains an Intent that starts an Activity of our app.

Here is the example of defining an action inside of notification using the PendingIntent object.

NotificationCompat.Builder nBuilder =  new NotificationCompat.Builder(this)
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);
nBuilder.setContentIntent(pendingIntent);




Once we are done with creation of notification, we need to pass a notification to the system by using NotificationManager.notify() method and we need to specify a ID in the notification to use this ID to update a notification later if required.

Here is the example of sending a notification to the system using the Notificationmanager.notify() method.

NotificationCompat.Builder nBuilder =  new NotificationCompat.Builder(this);
int mNotificationId = 999;
NotificationManager mNotifyMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, nBuilder.build());

How do you close/hide the Android soft keyboard programmatically?

 I created one function hideKeyboard  to hide keyboard on application class,


public class AppController extends Application {
    private static AppController appController;

    public static synchronized AppController getInstance() {
        return appController;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        appController = this;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        MultiDex.install(newBase);
    }
    public void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = activity.getCurrentFocus();
        if (view == null)
            view = new View(activity);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    } 
}


 I an calling hideKeyboard function on my Activity and Fragment pages like,


    AppController.getInstance().hideKeyboard(getActivity());

Create autofit view android

    We are going to create a view like this,




We can create view using FlexBoxLayout, 


Add the following dependency to your build.gradle file:

dependencies {
    implementation 'com.google.android:flexbox:1.1.0'
}



Adding the
FlexBoxLayout to the layout,


                        
<com.google.android.flexbox.FlexboxLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                app:flexDirection="row"
                app:flexWrap="wrap"
                app:justifyContent="flex_start">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="2dp"
                    android:text="Sample Text 1" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="2dp"
                    android:text="Sample Text 2"  />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="2dp"
                    android:text="Sample Text 3" />
            </com.google.android.flexbox.FlexboxLayout>

How to pass Object Array on retrofit request?

 For passing Object Array on retrofit requestwe will use @FieldMap 

Create Object,

public class ItemsList {
    @SerializedName("id")
    private int id;
    @SerializedName("Amount")
    private int Amount;
    @SerializedName("Notes")
    private String Notes;
    @SerializedName("serviceId")
    private int serviceId;
    @SerializedName("TypeId")
    private int TypeId;
}


Create Object Array,


        Order.Orderitems orderitems;
        Map<String, String> parms = new HashMap<String, String>();
        for (int i = 0; i < orderItems.size(); i++) {
            orderitems = orderItems.get(i);
            parms.put("ItemsList[" + i + "][id]", String.valueOf(orderitems.getId()));
            parms.put("ItemsList[" + i + "][Amount]", String.valueOf(orderitems.getAmount()));
            parms.put("ItemsList[" + i + "][Notes]", "");
            parms.put("ItemsList[" + i + "][serviceId]", String.valueOf(orderitems.getServiceId()));
            parms.put("ItemsList[" + i + "][TypeId]", String.valueOf(orderitems.getServiceTypeId()));
        }


API  Call

@FormUrlEncoded
@POST("api/shidhin/UpdateOrder")
Call<CommonResponse> updateOrderItems(@Header("Authorization") String token, @Field("OrderId") int orderid, @FieldMap Map<String, String> parms);
 

Create directory automatically on SD card

If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:


// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);


Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card. Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.

UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:


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






Create a folder in android external storage directory

Create a folder in android External Storage Directory.



Add  Permission on manifest,

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


Here is the Code,


String folder_main = "NewFolder"; 

File f = new File(Environment.getExternalStorageDirectory(), folder_main); 

if (!f.exists()) 

    f.mkdirs();


 

If you wanna create a parent folder into that you can use this code: 


File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1"); 

if (!f1.exists()) 

       f1.mkdirs();