Monday, August 8, 2022

gradle dependancy structure

 Here's how we used to declare dependencies:

  • compile 'test.dependency:1.0.0'

Here are the new configurations which should replace compile:

  • implementation 'test.dependency:1.0.0' --> this dependency is only used within this module
  • api 'test.dependency:1.0.0' --> this dependency will also be available in any builds that depend on this module

Monday, September 21, 2020

Static content in screen bottom coming over the recyclerview

Bottomsheet in activity covering over the recyclerview content. 

After little search and different ways to fix it found workarround to tackle this. 

as follow. 


<android.support.v7.widget.RecyclerView
...
android:clipToPadding="false"
android:paddingBottom="72dp"
/>

Saturday, August 1, 2020

Memory leak in startactivityforresult

If we have to start Activity B in Activity A for result as follow 

We will call startActivityForResult from Activity A we will set some result in out activity B and return result.
But what if user presses back button on Activity B how should we handle this case.

I was running LeakCanary and found surprising result that it was always leaking my Activity B. reason is that it wasn't finishing and staying in memory even after returning to Activity B with Back Press.

So here is the solution that I found to resolve this. So quick fix is call method finishActivity with request code that you have passed while calling activity B. 

class ActivityA: AppCompatActivity(){

    private val requestCode = 1001

    fun startActivityB(){
    startActivityForResult(Intent(this, ActivityB::class.java).apply 
                {
                    putExtra("category_id", currentCategory._id)
                    putExtra("category_color", currentCategory.color)
                    putExtra("category_name", currentCategory.name)

                }, requestCode)
    }

    override fun onActivityReenter(resultCode: Int, data: Intent?) {
        super.onActivityReenter(resultCode, data)
        finishActivity(requestCode)
    }

}

Saturday, June 6, 2020

RxAndroid basic example

RxAndroid is flavour of reactive programming implementation for Android.

Base of reactive programming is Observer design pattern.

Let's understand Observer design pattern first.

Observer Design Pattern:
Observer design pattern is one of the behavioural design pattern. It's about communication between objects. In observer design pattern main object emits the change in it and all the object s who are observing to change in main object gets notification about it.


Friday, December 13, 2019

using Java, Kotlin and dagger together in project

If we are using java, kotlin and dagger together in project.

Follow this steps

kapt
Kapt is the Kotlin Annotation Processing Tool, and it’s in pretty good shape these days. If you want to be able to reference generated code from Kotlin, you need to use kapt. To do that, simply include the plugin in your build.gradle file with the line:


apply plugin: 'kotlin-kapt'







And in dependencies

kapt 'com.google.dagger:dagger-compiler:2.13'

Thursday, June 27, 2019

Block touch event in view

Add an onTouchEvent method to the view with top position then return true. True will tell the event bubbling that the event was consumed therefore prevent event from bubbling to other views.

protected boolean onTouchEvent (MotionEvent me) {
    return true;
}

For v1 you would do an import:
import android.view.View.OnTouchListener;
Then set the onTouchListener:

v1.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
});

Force hide soft keyboard

InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

difference between “px”, “dip”, “dp” and “sp”

  1. px
    Pixels - corresponds to actual pixels on the screen.
  2. in
    Inches - based on the physical size of the screen.
    1 Inch = 2.54 centimeters
  3. mm
    Millimeters - based on the physical size of the screen.
  4. pt
    Points - 1/72 of an inch based on the physical size of the screen.
  5. dp or dip
    Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
  6. sp
    Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommended you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

Tuesday, June 18, 2019

Running adb over wifi

Easy Steps for running adb over wifi

1.  Connect Android phone and host machine to same WiFi network

2.  Connect Android phone to host machine using USB cable (to start with)

3.   Run adb tcpip 5555 from a command prompt

4.   Run adb shell "ip addr show wlan0 | grep -e wlan0$ | cut -d\" \" -f 6 | cut -d/ -f 1" to obtain the phone's IP address

5.   Disconnect USB cable and run adb connect :5555

Thursday, September 20, 2018

Android Kernel

Android Kernel

The Android kernel starts in a similar way as the linux kernel.  As the kernel launches, is starts to setup cache, protected memory, scheduling and loads drivers. When the kernel finishes the system setup, it looks for “init” in the system files.

What is the difference between the linux and android kernels?, here's a list of changes/addons that the Android Project made to the Linux kernel:

  • Binder: It is an Android specific interprocess communication mechanism and remote method invocation system.
  • ashmem:  "Android Shared Memory". It is a new shared memory allocator, similar to POSIX SHM but with a different behavior and sporting a simpler file-based API.
  • pmem: "Process memory allocator": It is used to manage large (1-16+ MB) physically contigous regions of memory shared between userspace and kernel drivers.
  • logger:  This is the kernel support for the logcat command.
  • wakelocks: It is used for power management files. It holds the machine awake on a per-event basis until wakelock is released.
  • oom handling: It kills processes as available memory becomes low.
  • alarm manager: It lets user space tell the kernel when it would like to wake up.
  • RAM_CONSOLE: Allows to save kernel printk messages to a buffer in RAM, so that after a kernel panic they can be viewed in the next kernel invocation.
  • USB gadget driver for ADB
  • yaffs2 flash filesystem

Tuesday, May 10, 2011

What is the NDK?

The Android NDK is a toolset that lets you embed components that make use of native code in your Android applications.
Android applications run in the Dalvik virtual machine. The NDK allows you to implement parts of your applications using native-code languages such as C and C++. This can provide benefits to certain classes of applications, in the form of reuse of existing code and in some cases increased speed.
The NDK provides:
  • A set of tools and build files used to generate native code libraries from C and C++ sources
  • A way to embed the corresponding native libraries into an application package file (.apk) that can be deployed on Android devices
  • A set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5. Applications that use native activities must be run on Android 2.3 or later.
  • Documentation, samples, and tutorials
The latest release of the NDK supports these ARM instruction sets:
  • ARMv5TE (including Thumb-1 instructions)
  • ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for NEON/VFPv3-D32 instructions)
Future releases of the NDK will also support:
  • x86 instructions (see CPU-ARCH-ABIS.HTML for more information)
ARMv5TE machine code will run on all ARM-based Android devices. ARMv7-A will run only on devices such as the Verizon Droid or Google Nexus One that have a compatible CPU. The main difference between the two instruction sets is that ARMv7-A supports hardware FPU, Thumb-2, and NEON instructions. You can target either or both of the instruction sets — ARMv5TE is the default, but switching to ARMv7-A is as easy as adding a single line to the application's Application.mk file, without needing to change anything else in the file. You can also build for both architectures at the same time and have everything stored in the final .apk. Complete information is provided in the CPU-ARCH-ABIS.HTML in the NDK package.
The NDK provides stable headers for libc (the C library), libm (the Math library), OpenGL ES (3D graphics library), the JNI interface, and other libraries, as listed in the Development Tools section.

Wednesday, February 9, 2011

Mobile

Mobile is electronic device used to connect peoples across multiple regions.

OpenGL

OpenGL a well knows platform for graphics development. To create 3d games or apps in android we have to use opengl

Friday, May 28, 2010

Let's make a call


Now we know when we're close to our friends, what are we likely to want to do when we're close? Drop in! But we're polite so we'll call them first. Let's change our list item click function to call the friend we've clicked. We can do this by firing a DIAL_ACTION intent.
    Intent i = new Intent(); i.setAction(DIAL_ACTION); i.setData(new ContentURI(numbers.get(position))); startActivity(i);
The phone dialer has registered an IntentReceiver filtered onDIAL_ACTION so it will react to this.

Set up a map activity and create an overlay to show where you are in relation to your friends


Half of the fun in having location sensitive information is drawing it on a map. Create a new activity class to display a map centered on our current location with markers at our friends locations. While we're at it we can draw a line from our position to each of our friends.
The map control itself is called a MapView, but we can only use aMapView in a MapActivity, so we'll change the inheritance of this activity to MapActivity.
    public class MyMapViewActivity extends MapActivity
To display the map we need to create a new MapView and set it as the content for our activity in the OnCreate method.
    MapView mapView = new MapView(this); setContentView(mapView);
This will make the MapView fill the entire screen, so use views likeLinearLayout if we want to create a more complicated UI layout.
We'll want to get access to the OverlayController and MapController, so create global variables to store them and assign the references within the OnCreate method. We'll also be using the Locationinformation, so get a reference to that too. With the references assigned set your map zoom and starting location using theMapController. When you're finished OnCreate should look something like this.
    protected void onCreate(Bundle icicle) {
      super.onCreate(icicle); MapView mapView = new MapView(this); mapController = mapView.getController(); overlayController = mapView.createOverlayController(); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mapController.zoomTo(9); setContentView(mMapView); updateView();
    }
updateView is where we do the work. Start by getting our current location and convert the Lat/Long to a map Point, then centre the map on our current location.
    Double lat = location.getLatitude()*1E6; Double lng = location.getLongitude()*1E6; Point point = new Point(lat.intValue(), lng.intValue()); mapController.centerMapTo(point, false);
The only thing left to do on our map is draw markers and link them up with lines. To do this you need to create a new class that extends Overlay, and add this using the OverlayController.
    MyLocationOverlay myLocationOverlay = new MyLocationOverlay(); overlayController.add(myLocationOverlay, true);
The work in the Overlay class is done by overriding the draw method.
    protected class MyLocationOverlay extends Overlay {
      @Override public void draw(Canvas canvas, PixelCalculator calculator, boolean shadow) {
        ... [ draw things here ] ...
      }
    }
I start by drawing a 'marker' on my current location. There doesn't seem to be support for 'traditional' Google Maps markers but you can achieve the same thing by drawing on the map canvas; I chose to draw small circles as markers. First you need to use thePixelCalculator to convert your Lat/Long points to screen coordinates, then create a Paint object to define the colours and settings for your brush. Then paint your markers.
    int[] screenCoords = new int[2]; calculator.getPointXY(point, screenCoords); RectF oval = new RectF(...); Paint paint = new Paint(); paint.setARGB(200, 255, 0, 0); canvas.drawOval(oval, paint);
I add my friends locations the same way as before, iterating over my address book grabbing names and locations. I filter out anyone too far away (say 10km) and draw markers, names (drawText), and joining lines (drawLine) to those nearby.

Refresh our list when we move


Given the location sensitive nature of WamF it makes sense to update the display whenever we move. Do this by asking theLocationManager to trigger a new Intent when our location provider notices we've moved.
    List providers = locationManager.getProviders(); LocationProvider provider = providers.get(0); Intent intent = new Intent(LOCATION_CHANGED); locationManager.requestUpdates(provider, minTime, minDistance, intent);
Intents in Android are like events in traditional event driven programming, so we're triggering a LOCATION_CHANGED event/intent every time we move by a minimum distance after a minimum time. The next step is to create an IntentReceiver (event handler), so create a new internal class that extends IntentReceiver and override the ReceiveIntent event to call our update method.
    public class myIntentReceiver extends IntentReceiver {
      @Override public void onReceiveIntent(Context context, Intent intent) {
        updateList();
      }
    }
We then have our activity listen for a LOCATION_CHANGED intent by registering the event handler and specifying the intent it should be listening for (LOCATION_CHANGED). Do this in the onCreate method or create a new menu option to start/stop the automatic updates.
    filter = new IntentFilter(LOCATION_CHANGED); receiver = new myIntentReceiver(); registerReceiver(receiver, filter);
Keep your phone running light by registering / unregistering the receiver when the activity Pauses and Resumes – there's no point in listening for location changes if we can't see the list.

Iterate over the address book pulling out names, locations, and phone numbers


A less publicized feature of Android is the ability to share content between applications. We're going to use this feature to populate our List with our contacts' names and their current distance from our phone so we create an updateList method that we call after we've gotten our current location.
Use the ContentResolver to return a query that provides access to data shared using Content Providers. Queries are returned ascursors that provide access to the underlying data tables. The data we're interested in is accessed using the People content provider.
    Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null); startManagingCursor(c);
The Cursor is a managed way of controlling your position (Row) in the underlying table. We get access to the data by specifying the column that holds the information we're after. Rather than memorising the column index for each Content Provider we can use constants from the People class as a shortcut.
    int coordIdx = c.getColumnIndex(People.NOTES); int phoneIdx = c.getColumnIndex(People.PhonesColumns.NUMBER); int nameIdx = c.getColumnIndex(People.NAME);
Now iterate over the table using the cursor storing the results in arrays. You'll note that we're pulling our contacts' location from theNotes field. In reality we'd want to figure this out based on their address using a geocoding lookup.
    List listItems = new ArrayList(); c.first(); do {
      String name = c.getString(nameIdx); String coords = c.getString(coordIdx); String phone = c.getString(phoneIdx); ... [ Process the lat/long from the coordinates ] ... ... [ Storing their location under variable loc ] ... String distStr = String.valueOf(location.distanceTo(loc)/1000); name = name + " (" + distStr + "km)"; listItems.add(name); numbers.add("tel:" + phone);
    } while(c.next());
Then we assign our list of strings to the array using an ArrayAdapter.
    ArrayAdapter notes = new ArrayAdapter(this, R.layout.notes_row, items); setListAdapter(notes);

Android Concepts

Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.

What is an action?
A description of something that an Intent sender desires.

What is activity?
A single screen in an application, with supporting Java code.

What is intent?
A class (Intent) describes what a caller desires to do. The caller sends this intent to Android's intent resolver, which finds the most suitable activity for the intent.

How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.

What languages does Android support for application development?
Android applications are written using the Java programming language.

What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.

Use the Location Based Services to figure out where we are and request updates when we move


Possibly the most enticing of the Android features are the Location Based Services that give your application geographical context through Location Providers (GPS etc). Android includes a mock provider called 'gps' that marches back and forth through San Fransisco. Alternatively you can create your own mock providers in XML.
You use the LocationManager to find your current position.
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getCurrentLocation("gps");