Routing Module Path Order

All you need to know is there will be app-routing-model.ts which will include all the paths in the application. When there is an independent feature, it is always good to have separate routing module for the feature. If you have app module and device module, then you can have nested routing table
Your app-routing-module will include

{ path:‘devices’,  loadChildren:‘../device/device.module#DeviceModule’}

Point 1:

In your device-routing-module you will have

{path:’newdevice’, component:DeviceAddnewComponent}

By the above, http://localhost:4200/#/devices/newdevice => will open DeviceAddNewComponent.

Point 2:

As we already know, if we need a dynamic parameter to be added the routing path looks like below:
http://localhost:4200/#/devices/12345 , where 12345 = id and it will open DeviceStatusComponent

{ path:’:id’, component: DeviceStatusComponent},

But if you add paths in the below order:

{ path:’:id’,component: DeviceStatusComponent },
{ path:‘location’, component:DeviceLocationComponent}

Both, http://localhost:4200/#/devices/12345 and http://localhost:4200/#/devices/location will open DeviceStatusComponent.

So always it needs to be remembered that the order of path is important for url resolution.

Correct one is

{ path:’location’, component:DeviceLocationComponent,
{ path:‘:id’,component:DeviceStatusComponent }

http://localhost:4200/#/devices/12345 will open DeviceStatusComponent.
And http://localhost:4200/#/devices/location will open DeviceLocationComponent

Sending static data – to components

I had an issue of setting the static tool bar title to the web page navigated.

Then realised there was an data field which can be set in the routing file.

Step 1: Add data to the route
const routes: Routes = [
    { path: '', component: SampleComponent, 
            data: { toolbar_title:'Toolbar title' } }
];
Step 2: Read the data from the component.ts
export class SampleComponent implements OnInit {

  toolbar_title: string

  ngOnInit() {
    this.route.data.subscribe(
      (data: { toolbar_title: string }) => {
         this.toolbar_title=data.toolbar_title;
      });
  }

}

 

Step 3: Use the data in the component.html

<app-comp [toolbar_title]=toolbar_title></app-comp>

Commands for modules and routing

When creating a PWA, I was not sure of the module and component concepts. Had a belief there should be only one routing. Then working on the project as it grew understood maintaining it as one is an head ache, modularising it will help. Since most of the code was written the following command came in handy for converting the existing folder to modules and components.

  • Converting an existing folder to module:   ng g module <foldername>
  • If routing is needed:  ng g module <foldername> —routing
  • If module exists and need to add only routing:  ng g module <routing-file> –module <modulename>

Sp & Wp

What is sp & wp?

sp – smart pointer(cpp) equivalent to strong reference(java)

In strong references, the object cannot be garbage collected by the collector unless the reference to it does not exist.

wp – weakpointer(cpp) equivalent to weakreference(java)

But in weak references, the collector can collect the object when it is necessary even when there is a weak reference associated with it.


Why we need?

Because the Android is java based, and java includes strong and weak references to facilitate garbage collection. In cpp, to get the same functionality we use sp and wp.

Things to know:

  1. If you want to use sp and wp, then the class should inherit RefBase.
  2. If wp should be converted to sp, use weakptr.promte()
  3. You have weak and strong reference to an object, when the strong reference is removed the weak reference becomes out of scope.
  4. There is a strong ref count and weak ref count maintained separately. And initial value of strong ref count is 1<<28.

Communication between service and activity – Part 3

After a long time, I found out that Messenger can also be used to communicate between Activity and Services.

What does this Messenger mean?
    It is a Parcelable type, which carries messages from service to activity and vise vera.
    It is similar to aidl, which can work between two different processes.

Quick example how to implement them.
Create a service on launching the activity. On clicking the button in the

Activity:
1. It will have an handler which is responsible for handling all the messages from the service
private class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        String str = (String)msg.obj;
        Toast.makeText(getApplicationContext(),
            "From Service -> " + str, Toast.LENGTH_LONG).show();
    }
}

2. Create a class implementing ServiceConnection Interface
class MyServiceConnection implements ServiceConnection {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mServiceMessenger = new Messenger(service);
        // where mServiceMessenger is used to send messages to Service
        // service is the binder returned from onBind method in the Service
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mServiceMessenger = null;
        unbindService(mCon);
    }
}

3. Create a Messenger Object in OnCreate method with the object of IncomingHandler class
Messenger mActivityMessenger;
mActivityMessenger = new Messenger(new IncomingHandler());

4. Start the service in the onCreate method
Intent lIntent = new Intent(MainActivity.this, MainService.class);
lIntent.putExtra("Messenger", mActivityMessenger);
startService(lIntent);

5. Bind to a service in OnResume method
@Override
protected void onResume() {
    super.onResume();
    Intent lIntent = new Intent(MainActivity.this, MainService.class);
    bindService(lIntent, mCon, 0); // mCon is an object of MyServiceConnection Class
}

6. Unbind the service in OnPause method to avoid Service leakage
@Override
protected void onPause() {
    super.onPause();
    unbindService(mCon);
}

7. Add a onClickListener to the button and send message to service on onClick event.
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "onClick");
        Message msg = new Message();
        msg.obj = "Hi service..";
        try {
            mServiceMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
});

NOTE:
1. Currently string is sent in the message as obj but when the activity and the service are in different process we need to send the string as bundle.
2. If there are more than one activity bound to the service then the service should have a arraylist of client registered and replyTo variable in Message should be set to that activity’s messenger.

Service:
1. It will have an handler which is responsible for handling all the messages from the Activity
private class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        String str = (String)msg.obj;
        Toast.makeText(getApplicationContext(),
    "From Activity -> " + str, Toast.LENGTH_LONG).show();
        Message lMsg = new Message();
        lMsg.obj="Hello Activity";
        try {
            mActivityMessenger.send(lMsg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

3. Create a Messenger Object in OnCreate method with the object of IncomingHandler class
Messenger mServiceMessenger;
mServiceMessenger = new Messenger(new IncomingHandler());

4. Get the extras from the messenger and save it in the local variable
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
    mActivityMessenger = intent.getParcelableExtra("Messenger");
    return super.onStartCommand(intent, flags, startId);
}

5. OnBind return the service messenger’s binder to the activity.
@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "onBind");
    return mServiceMessenger.getBinder();
}

Set Wallpaper

To set an image either from Gallery, Camera or Online link, there are three steps

1. Get an instance of the wallpaper manager as follows, with mActivity being the currenty Activity’s instance.
WallpaperManager mWallpaperManager = WallpaperManager.getInstance(mActivity);

2. To use wallpaper manager need to set the permission for it in AndroidManifest.xml
<uses-permission android:name="android.permission.SET_WALLPAPER" />

3. Then finally, set the bitmap – which sets the bitmap image as the wallpaper
mWallpaperManager.setBitmap(lBmp);
other than bitmap, there are other methods to set wallpaper directly from streams or from resource folder

Other things I learnt are as follows,
1. To avoid stretching of images, we need to use the following. It sets the wallpaper without resizing.
mWallpaperManager.suggestDesiredDimensions(lBmp.getWidth(), lBmp.getHeight());
For this we need to set permissions,
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />

2. To set the wallpaper to fit the screen resolution, we can resize the bitmap and then set it as follows.
scaledWallpaper = Bitmap.createScaledBitmap(lBmp,
mWallpaperManager.getDesiredMinimumWidth(),
mWallpaperManager.getDesiredMinimumHeight(),
false);
mWallpaperManager.setBitmap(scaledWallpaper);

Customize gallery view

We have seen how to make horizontal list using Gallery. In this, it is about customizing the Gallery view so that it can move one by one without the default scroll

Steps to be followed…

1. Create a java class extending the Gallery
-> implement the three constructors and do nothing
public class GalleryLayout extends Gallery {
    public GalleryLayout(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    public GalleryLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }
    public GalleryLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }
}

-> implement the OnFling and OnScroll method which is responsible for swipe activity. Instead of returning super methods just return false and it is done.
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
    return false; //super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
    return false;// super.onScroll(e1, e2, distanceX, distanceY);
}


2. In xml , instead of creating a view which is Gallery, create a view with the custom class name

In the below example, com.sample.app is the package name and GalleryLayout is the class name as you know.

Similarly, you can implement any method and change the default functionality.

Now, we need to move to next image and before image. For that,

1. Get the Gallery view
GalleryLayout mGallery = (GalleryLayout)findViewById(R.id.imageGallery);

2. Two buttons – right and left and OnClick of the two buttons implement the following two methods.
In the methods – getSelectedPosition returns the current position visible in the Gallery view.

public void onRightClicked() {
    if(mGallery.getSelectedItemPosition() < mGallery.getCount()) {         mGallery.setSelection(mGallery.getSelectedItemPosition() + 1);
    }
}
public void onLeftClicked() {
    if(mGallery.getSelectedItemPosition() > 0) {
        mGallery.setSelection(mGallery.getSelectedItemPosition() - 1);
    }
}

Done.. 🙂

Current Location Update

Android offers so many API to find the location till froyo version we had only request location updates and it will eat up the battery with continuous updates.
There is a new API introduced in 2.3 to obtain single update of GPS.

An simple example to obtain location (single update) is as below:

  1. Register a receiver to listen to intent – “SINGLE_LOCATION_UPDATE_ACTION”
    registerReceiver(singleUpdateReceiver,new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));
  2. Get the instance of location manger service
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  3. Create criteria instance and set accuracy as required
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
  4. Create a pendingIntent instance. Pendingintent is registered to receive broadcast with action “SINGLE_LOCATION_UPDATE_ACTION” from the location manager
    Intent updateIntent = new Intent(SINGLE_LOCATION_UPDATE_ACTION);
    singleUpatePI = PendingIntent.getBroadcast(this, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
  5. Finally, request for single update
    locationManager.requestSingleUpdate(criteria, singleUpatePI);
  6. We need to declare the receiver with onReceive function as below
    protected BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG,"onReceive");
    //unregister the receiver so that the application does not keep listening the broadcast even after the broadcast is received.
            context.unregisterReceiver(singleUpdateReceiver);

    // get the location from the intent send in broadcast using the key - this step is very very important
            String key = LocationManager.KEY_LOCATION_CHANGED;
            Location location = (Location)intent.getExtras().get(key);

    // Call the function required
            if (location != null) {
                onLocationChanged(location);
            }

    // finally remove the updates for the pending intent
            locationManager.removeUpdates(singleUpatePI);
        }
    };

PendingIntent Explanation

Why Pending Intent?

They are used when the control moves onto another application to perform certain activity like -> when we need to use alarm manager or NFC Service

Usage of Alarm Manager – when we need a certain action to be performed at certain point of time

Getting an instance of PendingIntent

    There are three main ways

  1. getService() – launches a service
    Example:
    Intent lIntent = new Intent(this,AlertService.class);
    PendingIntent refreshIntent = PendingIntent.getService(this,0,lIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    Explanation:
        This lauches AlertService.
    Parameter Explanation:
        this – current context
        0 – any integer value – unique for identification
        lIntent – intent to be launched as a result
        FLAG_UPDATE_CURRENT – which indicates if there is an pending intent already, delete the prev and include this.
  2. getActivity() – launches the activity
    Example:
    Intent lIntent = new Intent(this,AlertActivity.class);
    PendingIntent refreshIntent = PendingIntent.getActivity(this,0,lIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Explanation:
        This lauches AlertActivity.
  3. getBroadcast() – receives a broadcast
    Example:
    Intent lIntent = new Intent(APP_UPDATE);
    PendingIntent refreshIntent = PendingIntent.getBroadcast(this,0,lIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    Explanation:
        This receives the broadcast – u need to register the broadcast either in the manifest file or activity launched.
    Parameter Explanation:
        APP_UPDATE – string value – denotes the action for broadcast

Display app while the screen is locked

You can easily disable keyguard from your application.

All you need is two lines of code :

1. Get the window instance
Window w = getWindow(); // from OnCreate of activity

2. set the flag – FLAG_SHOW_WHEN_LOCKED
w.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

This will display the activity and then on back it will enable the lock again.

But if we require to disable the keyguard meaning it will not lock after that activity is displayed, we need to follow the below approach

1. Create an instance of Keyguard manager
KeyguardManager mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
2. Create a new lock
KeyguardLock newKeyguardLock = mKeyGuardManager.newKeyguardLock("screenunlock");
3. Disable the lock
newKeyguardLock.disableKeyguard();

To enable it back just follow the below:
newKeyguardLock.reenableKeyguard();