InfyOm Blog

latest-post

Last week, we run into a problem for one of the large Gatsby + ReactJS + Laravel projects in hosting which is hosted with Apache Webserver on Amazon AWS EC2. The problem we were facing was, for some reason, when we reload the Gatsby website, it was giving a 404 error page.

If you open a home page and then a normal visit then the website will fully function, but if you reload the page then it gives an error. And we found it happens when we are using Dynamic routing of React Route in Gatsby as per show in Gatsby documentation here.

Also, what we found, if we test the website build with gatsby serve then it works fine. But while using Apache, it behaves differently and we found that this problem has been faced by lots of people over the internet.

So what we came up with is, we used gatsby serve with an apache proxy. Here is how we did it,

Step 1 - Setup Project

As a first step, clone the project on the server and run a command, gatsby build to create a gatsby build.

Step 2 - Setup PM2 for Gatsby Serve

The next step that we need to do is run gatsby serve. But as you know, we can not run this command directly via console, because as you exit from the console, the command will be terminated.

So we will be using pm2 package, a NodeJS utility that is used to run nodejs apps.

For that, we will need to install pm2 globally. Run the following command to install it,

npm install pm2 -g

You can find other installation ways here if you need.

Once the installation has been done, let's run the gatsby serve command via pm2. For that run the following command from the gatsby project folder,

pm2 start gatsby --name my-web-app -- serve

where my-web-app you can replace with the name of your app.

Once, it's running, try to test it, if it's working correctly by opening the URL http://your-ip-address:9000/. Make sure, port 9000 is opened on your server for traffic.

Step 3 - Configure Apache

Once, gatsby serve is working and tested. The next step is to configure apache to proxy all port 80 traffic to port 9000.

For that, edit your apache conf file (or virtual host conf file), and add the following lines (or configure it to something like the following),

<VirtualHost *:80>
        ServerName my-web-app.infyom.com

        ServerAdmin webmaster@infyom.com

        ProxyRequests On
        ProxyPass / http://localhost:9000/
        ProxyPassReverse / http://localhost:9000/

        ErrorLog ${APACHE_LOG_DIR}/my-web-app.infyom.com.error.log
        CustomLog ${APACHE_LOG_DIR}/my-web-app.log combined

        ......
        # any other options below as per your need
        ......
</VirtualHost>

The next step you need to do is restart your apache server by,

sudo service apache2 restart

And then you can just open the URL https://my-web-app.infyom.com and it should work fine.

Bonus

New Deployment

Whenever you deploy a new code, you again need to run gatsby build and then pm2 restart my-web-app. Then only it will take new changes.

Troubleshooting

Sometimes, we found that we need to restart apache as well after the new deployment. so if you run into any trouble, then make sure to restart apache as well and it should solve the problem.

I hope it may help you to resolve your 404 problem.

July 16, 20213 minutesuserMitul Golakiya

Posts

post
Nowdays, laravel livewire is becoming more trendy for geeks. as most of developers are using it, more and more issues they are facing while developing the products. one of them is searching the records. 

Recently we have developed the livewire common searchable component which makes your searching easier, as you can specify which fields you want to search by just giving the field name into the component.

What you have to do is just create SearchableComponent a class into your App\Http\Livewire directory.  just copy the following class on the given namespace.

<?php

namespace App\Http\Livewire;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Livewire\Component;
use Livewire\WithPagination;
use Str;

abstract class SearchableComponent extends Component
{
    use WithPagination;

    /**
     * @var string
     */
    public $search = '';

    /**
     * @var int
     */
    protected $paginate = 12;

    /** @var Builder */
    private $query;

    /**
     * SearchableComponent constructor.
     *
     * @param $id
     */
    public function __construct($id)
    {
        parent::__construct($id);

        $this->prepareModelQuery();
    }

    /**
     *  Prepare query
     */
    private function prepareModelQuery()
    {
        /** @var Model $model */
        $model = app($this->model());

        $this->query = $model->newQuery();
    }

    /**
     * @return mixed
     */
    abstract function model();

    /**
     * Reset model query
     */
    protected function resetQuery()
    {
        $this->prepareModelQuery();
    }

    /**
     * @return Builder
     */
    protected function getQuery()
    {
        return $this->query;
    }

    /**
     * @param  Builder  $query
     */
    protected function setQuery(Builder $query)
    {
        $this->query = $query;
    }

    /**
     * @param  bool  $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    protected function paginate($search = true)
    {
        if ($search) {
            $this->filterResults();
        }

        $all = $this->query->paginate($this->paginate);
        $currentPage = $all->currentPage();
        $lastPage = $all->lastPage();
        if ($currentPage > $lastPage) {
            $this->page = $lastPage;
        }

        return $this->query->paginate($this->paginate);
    }

    /**
     * @return Builder
     */
    protected function filterResults()
    {
        $searchableFields = $this->searchableFields();
        $search = $this->search;

        $this->query->when(! empty($search), function (Builder $q) use ($search, $searchableFields) {
            $searchString = '%'.$search.'%';
            foreach ($searchableFields as $field) {
                if (Str::contains($field, '.')) {
                    $field = explode('.', $field);
                    $q->orWhereHas($field[0], function (Builder $query) use ($field, $searchString) {
                        $query->whereRaw("lower($field[1]) like ?", $searchString);
                    });
                } else {
                    $q->orWhereRaw("lower($field) like ?", $searchString);
                }
            }
        });

        return $this->query;
    }

    /**
     * @return mixed
     */
    abstract function searchableFields();
}
Now you have to extend your existing laravel component by SearchableComponent. let's say we already have Tags livewire component. and its looks like following.

<?php

namespace App\Http\Livewire;

use App\Models\Tag;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class Tags extends SearchableComponent
{
    public function render()
    {
        $tags = $this->searchTags();

        return view('livewire.tags', [
            'tags' => $tags,
        ])->with("search");
    }

    /**
     * @return LengthAwarePaginator
     */
    public function searchTags()
    {
        $this->setQuery($this->getQuery());

        return $this->paginate();
    }

    function model()
    {
        return Tag::class;
    }

    function searchableFields()
    {
        return [
            'name',
        ];
    }
}
So here we have extended our existing Tags component by SearchingComponent.  

In searchable fields you can specify the field name that you want to search. and replace the Model with your records Model.

That it. Now you don't need to write search queries again and again. just extend your livewire component by searchable component.

Here are some Interesting livewire tutorials that you need to check :


October 22, 20201 minuteauthorVishal Ribdiya
post
The technical skills outlined above are necessary for graphic designers to execute the actual tasks assigned to them. But there are several transferable skills needed in order to successfully bring an idea from concept to creation.
Our analysis helped us identify five important qualities employers are seeking in graphic design candidates. Here's what we found

Creativity:

This one probably goes without saying, but graphic designers are tasked with identifying creative solutions to deliver a message or solve a problem. This requires an innate ability to think outside the box and bring forth innovative ideas on a regular basis.
Creativity.png 184.09 KB
Analytical:

A graphic designer should be able to step outside their own mind and view the product or service analytically and from different perspectives. That way they can help anticipate how the audience will receive it.
Analytical.png 145.11 KB
Communication:

Graphic designers must possess strong written and oral communication skills in order to effectively work with team members and clients alike. Asking inquisitive questions helps them understand expectations so their designs will align with their client's vision.
Designers are often faced with the challenge of working on several projects with various deadlines at the same time. Being able to juggle multiple projects and meet stringent deadlines is essential to a successful design career.
Graphic design techniques and trends are constantly evolving, which means the learning is never done for designers. In order to ensure their designs are meeting client objectives, they need to be willing to dig up insights about their audience and explore new strategies.
Research.png 193.8 KB
October 19, 20201 minuteauthorKishan Savaliya
post

Introduction











Persuasion is a method of communication aimed at influencing the attitudes, beliefs, or behaviors of others. In terms of sales, understanding usually occurs when a sales representative tries to convince a prospect that their product or service is the best solution to their problem.
Let's review the persuasion strategy you can implement today to close your next deal.

1. Personalize your message













If you want to explain the possibility of considering your product, resist the request to follow the general sales script. When you make excessive rehearsal noise or don’t share messages or information that seems to suit your prospect, your efforts go to one ear and go to the other.
This doesn't mean you need to fully wing your sales calls, it does mean you need to be prepared to adjust your message based on what interests you in the potential.

2. Focus on problem-solving













Instead of telling the prospect all the reasons why they should buy your product (which may feel pressure and emotion), focus on sharing all the reasons why your product can help them solve their problem. By focusing on their concerns and locating your offer fur as a solution, you are showing the value of your product without excessive pressure.

3. Give social proof













Letting your past customers sell to you - knowing when to take advantage of social proof can be a powerful persuasive trick.
While buyers may take your point as a sales representative with a grain of salt because they know you want to sell, they are more likely to trust a testimonial or story from a previous customer who was looking for a similar solution.

4. Assume goals













Picture: You feel ready to call your sales call. You think you have a solid understanding of who the prospects are and what they are looking for. Your notes have been typed and you are ready to close the deal.
Then during a call, potentially throws out several turns, asking you questions and mentioning objections that you weren’t prepared to account for - the dream of every sales rip. But don't go too far. This is a valuable learning experience.

5. Empower empowerment decision making













After all, you want your customers to buy from you because they really want to, not because they feel pressured. And let’s be realistic - including your prospects, don’t like to tell anyone what to do, so you’ll avoid being too directive in your approach. As a sales representative, it is your job to provide the context and information that makes your product a thought-provoking product.

6. Make personal connections



It's a basic rule of human interaction - we're all ready to trust and engage with people we really love on a deeper level. While buyers can choose your product or brand as a sales representative, you are the main source of human engagement representing your company.

7. Don’t rush into the process













Last but not least, don't rush your prospect through the sales process. We get it - you have goals on a regular basis. However, effective persuasion should seem natural to the prospect. They do not feel pressured or rushed to sign the dotted line. This doesn’t mean you can’t implement a sense of urgency or be on time - in fact making a little sense of urgency (such as paying a special price for a limited time) can be an effective trick.
October 16, 20203 minutesauthorAnkit Kalathiya
post
 
Introduction to Bug Life Cycle
The fault life cycle or defect life cycle is the specific set of states that a fault goes through before it is closed or resolved. When a fault is detected - by a tester or someone else on the team - the life cycle provides a tangible way to track the progress of a bug fix, and during the fault's life multiple individuals touch it - directly or indirectly. Troubleshooting is not necessarily the responsibility of a single individual. At different stages of the life cycle, several members of the project team will be responsible for the error. This blog will help you understand how many cases the error goes through varies from project to project. The life cycle diagram covers all possible situations 

What’s The Difference Between Bug, Defect, Failure, Or Error?
Bug : If testers find any mismatch in the application/system in testing phase then they call it as Bug.
As I mentioned earlier, there is a contradiction in the usage of Bug and Defect. People widely say the bug is an informal name for the defect.
Defect : The variation between the actual results and expected results is known as defect.
If a developer finds an issue and corrects it by himself in the development phase then it’s called a defect.
Failure : Once the product is deployed and customers find any issues then they call the product as a failure product. After release, if an end user finds an issue then that particular issue is called as failure
Error : We can’t compile or run a program due to coding mistake in a program. If a developer unable to successfully compile or run a program then they call it as an error.

Software Defects Are Basically Classified According To Two Types :

Severity
Bug Severity or Defect Severity in testing is a degree of impact a bug or a Defect has on the software application under test. A higher effect of bug/defect on system functionality will lead to a higher severity level. A Quality Assurance engineer usually determines the severity level of a bug/defect.

Types of Severity
In Software Testing, Types of Severity of bug/defect can be categorized into four parts :
Critical: This defect indicates complete shut-down of the process, nothing can proceed further
Major: It is a highly severe defect and collapses the system. However, certain parts of the system remain functional
Medium: It causes some undesirable behavior, but the system is still functional
Low: It won't cause any major break-down of the system

Priority 
Priority is defined as the order in which a defect should be fixed. Higher the priority the sooner the defect should be resolved.
Priority Types
Types of Priority of bug/defect can be categorized into three parts :
Low: The Defect is an irritant but repair can be done once the more serious Defect has been fixed
Medium: During the normal course of the development activities defect should be resolved. It can wait until a new version is created
High: The defect must be resolved as soon as possible as it affects the system severely and cannot be used until it is fixed

(A) High Priority, High Severity
 An error which occurs on the basic functionality of the application and will not allow the user to use the system. (E.g. A site maintaining the student details, on saving record if it, doesn't allow to save the record then this is high priority and high severity bug.)

(B) High Priority, Low Severity
 High Priority and low severity status indicates, defect have to be fixed on immediate bases but does not affect the application while High Severity and low priority status indicates defect have to be fixed but not on immediate bases.

(C) Low Priority Low Severity
A minor low severity bug occurs when there is almost no impact on the functionality, but it is still a valid defect that should be corrected. Examples of this could include spelling mistakes in error messages printed to users or defects to enhance the look and feel of a feature.

(D) Low Priority High Severity
This is a high severity error, but it can be prioritized at a low priority as it can be resolved with the next release as a change request. On the user experience. This type of defect / defect can be classified in the category High severity but Low priority. 

Bug Life Cycle
buglifecycle.PNG 45.1 KB


New: When a new defect is logged and posted for the first time. It is assigned a status as NEW.
Assigned: Once the bug is posted by the tester, the lead of the tester approves the bug and assigns the bug to the developer team
Open: The developer starts analyzing and works on the defect fix
Fixed: When a developer makes a necessary code change and verifies the change, he or she can make bug status as "Fixed."
Pending retest: Once the defect is fixed the developer gives a particular code for retesting the code to the tester. Since the software testing remains pending from the testers end, the status assigned is "pending retest."
Retest: Tester does the retesting of the code at this stage to check whether the defect is fixed by the developer or not and changes the status to "Re-test."
Verified: The tester re-tests the bug after it got fixed by the developer. If there is no bug detected in the software, then the bug is fixed and the status assigned is "verified."
Reopen: If the bug persists even after the developer has fixed the bug, the tester changes the status to "reopened". Once again the bug goes through the life cycle.
Closed: If the bug is no longer exists then tester assigns the status "Closed."
Duplicate: If the defect is repeated twice or the defect corresponds to the same concept of the bug, the status is changed to "duplicate."
Rejected: If the developer feels the defect is not a genuine defect then it changes the defect to "rejected."
Deferred: If the present bug is not of a prime priority and if it is expected to get fixed in the next release, then status "Deferred" is assigned to such bugs
Not a bug:If it does not affect the functionality of the application then the status assigned to a bug is "Not a bug".

Defect Life Cycle Explained
1. The tester finds the defective status assigned to the defect. 
2. A defect is forwarded to the project manager for analysis.  
3. The project manager decides whether a defect is valid. 
4. Here the defect is invalid. The status is "Rejected". 
5. The project manager assigns a rejected status.  
6. If the bug is not resolved, the next step is to check that it is in scope. 
Suppose we have another function - email functionality for the same application, and you find a problem with it. However, it is not part of the current version if such errors are assigned as a deferred or deferred status. 
7. Next, the manager checks to see if a similar error has occurred earlier. If so, a duplicate status is assigned to the error.  
8. If not, the bug is assigned to the developer, who starts correcting the code. 
9. During this phase, the defect is assigned a status in process, 
10. Once the code is fixed. A defect is assigned a status fixed.
11. Next, the tester tests the code again, If the test case is passed, the defect is closed. If the test cases fail again, the bug is reopened and assigned to the developer.
12. Consider a situation where, during the first release of the flight reservation, an error was detected in the fax order, which has been fixed and a status of closed has been assigned. The same error occurred again during the second upgrade version. 
In such cases, a closed defect is opened again.  

"That's all to Bug Life Cycle" 
October 13, 20206 minutesauthorBhumi Khimani
post
Here we will learn, how to export annotation drawn using PDFTron.

Events for export annotation

When we draw any annotation "annotationChanged" event will be fired, then we cache that event and we can export that annotation using "exportAnnotations".
When we draw annotation we'll save them in the database and when we reload the same document we can retrieve saved annotations from database and can again show them, we will learn that in my next blog post.
Here is example of how to save and annotation in database.

Example

WebViewer({
    path: 'path_to_the_PDFTron_'lib'_folder_on_your_server',
    css: 'webviewer_css',
    licenseKey: 'YOUR_PDF_TRON_LICENSE_KEY',
    initialDoc: 'YOUR_FILE URL' //url of a file to load
}, document.getElementById('viewer'))
    .then(function (instance) {
        let docViewer = instance.docViewer;
        let annotManager = instance.annotManager;
       
        annotManager.on('annotationChanged', (annots, action, e) => {
            if (e.imported) return;

            annotManager.exportAnnotations({
                links: false,
                widgets: false,
                annotList: annots
            }).then(function (xfdfStrings) {

                annots.forEach(function (annot) {
                    if (action === "delete") {
                        deleteAnnotation(annot.mu);
                    } else {
                        saveAnnotation(annot.mu, xfdfStrings);
                    }
                });

                if (action === "add") {
                    annotManager.selectAnnotation(annots[0]);

                    if (annots[0]['Subject'] !== 'Comment') {
                        // to open comment box
                        document.getElementById('viewer').childNodes[0].contentWindow.document.querySelector('div[data-element="annotationCommentButton"]').click();
                    }
                }
            });
        });
    });

let saveAnnotation = function (annotationId, annotationXfdf) {
    let saveAnnotationUrl = '';
    if (fromExtension) {
        saveAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    } else {
        saveAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    }

    $.ajax({
        url: saveAnnotationUrl,
        type: 'POST',
        data: {annotation: annotationXfdf},
        success: function (result) {
            console.log(result);
        },
        error: function (result) {
            console.log(result);
        }
    });
};

let deleteAnnotation = function (annotationId) {

    let deleteAnnotationUrl = '';
    if (fromExtension) {
        deleteAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    } else {
        deleteAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    }

    $.ajax({
        url: deleteAnnotationUrl,
        type: 'DELETE',
        success: function (result) {
            console.log(result);
        },
        error: function (result) {
            console.log(result);
        }
    });
};
October 10, 20201 minuteauthorMonika Vaghasiya
post
In the previous article, we learned 6 areas or tips on How to increase profits in our business - part 1.

In this article, we will learn more about how to increase profit in our business. Maximizing Profit depends on the strategies that business owners take. There are only two ways to do this:
1. Increase Prices
2. Reduce Cost.

You simply cannot say that you are going to increase the profit of your business without a specific strategy. All you can do to increase profit is to improve the variables that ultimately determine your Profitability. Let's see 7 more points to increase profit.

7. Know your sales Channel




To stimulate your sales channel, you need to generate excitement and a reason to buy. This can be done by introducing vibrant, brightly colored sales that include all your products and services and by expressing a sense of urgency, encouraging sales partners, and adding subscription sales.

8. Find a new Customer




Follow up after meetings. Contact the people you meet to see if they are likely. If they say they no longer need your services, ask them when it's a good time to call, or if they have business associates who can use what you sell now.

9. Remove unprofitable service and product




If you have more than one product or service, any analysis will determine if one is more profitable than the other. If you have a lot of products in your offering, you can trust that some of them will not make money. The trick is to find out what they are and then put in motion plans to eliminate them. The basic tool for doing this is an orderly list that ranks all your products and services showing total revenue and all direct costs and total profits.

10. Reduce labor costs with part-time workers




Employment is lower than full-time workers than part-time workers. Take advantage of this luxury by hiring multiple part-time workers. Warn that if these people are presented to your company with a full-time opportunity they will leave them first.

11. Develop a CEO monthly letter to employees to create teamwork and communication




You'll want to have monthly conversations with your team, letting them know about any updates, highlighting individual performances, and reminding them of goals for the quarter and year. This will help build team morale and focus on expectations.

12. Invest in your people




Your team will only be able to make exceptional work progress and be competent when you invest in their improvement. Invest in their continuing education and also provide the best resources to do their job effectively.

13. Send personal notes of congratulations or thank employees at their home




When you send complimentary notes to employees ’homes, it shows that you think of them as a person rather than just a worker. This helps increase employee loyalty to your company.

That's it. If you want to run a profitable business, take these tips and apply them to your business. It will help your business perform better, keep growing, and increase profits.
October 09, 20202 minutesauthorAnkit Kalathiya
post
Hello, wonderfully friends today in this blog in learning in android XML file creating different type shape creating. A shape is an XML file that defines a geometric shape, including strokes, colors, and gradients


First Creating .xml file :

  • 1.Open android studio
  • 2.Go to drawable 
  • 3.right click drawable menu
  •  flow below image steps:


Now friend starts coding :


  • -Creating a capsule shape flow below code:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

  <corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:radius="60dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />

  <solid android:color="#CFCFCF" />

  <padding
    android:bottom="0dp"
    android:left="0dp"
    android:right="0dp"
    android:top="0dp" />

  <size
    android:height="60dp"
    android:width="270dp" />
 
</shape>


Corners:

  • The below image is showing the shape corner radius
Solid :

  • -Solid means shape inner color “#CFCFCF”

Padding:

- There is always confusion developer between padding and margin. Both provide extra space/gap inside or outside the container. In simple words, margin means to push outside, whereas padding means to push inside.

Size:

  •  Its very simple shape width - height 
October 07, 20201 minuteauthorPankaj Valani
post
Today I’m going to write on Create Floating Widget never stop closing the app from the background. First of all, you must know what is the service in Android.

What is a service in Android?

A service is a component that runs in the background without direct interaction with the user. Since the service has no user interface, it is not bound to the life cycle of the activity. If you want to repeat a task, using the service is the best way.
Service stops are one of the biggest problems when you clear the application from background functions.


My service is below:

public class FloatingViewService extends Service  {

    private WindowManager mWindowManager;
    private View mFloatingView;
    private View floatingButton;
    private final static float CLICK_DRAG_TOLERANCE = 10;

    private float downRawX, downRawY;
    private float dX, dY;
    int LAYOUT_FLAG;
    private SpeechRecognizer speechRecognizer;

    public FloatingViewService() {
    }
		Context context;

    public FloatingViewService(Context applicationContext) {
        super();
        context = applicationContext;
        Log.i("HERE", "here service created!");
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
					 KeyguardManager myKM = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
              if( myKM.inKeyguardRestrictedInputMode()) {
                  Intent i = new Intent(this,FloatingViewService.class);
                  startService(i);
//            //it is locked
                } else {
                    Intent i = new Intent(this, FloatingViewService.class);
                    startService(i);
        //it is not locked
             }
            return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_layout, null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
        }

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                LAYOUT_FLAG,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mWindowManager.addView(mFloatingView, params);

        floatingButton.setOnTouchListener(new View.OnTouchListener() {
            private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = params.x;
                        initialY = params.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();

                        downRawX = event.getRawX();
                        downRawY = event.getRawY();
                        dX = v.getX() - downRawX;
                        dY = v.getY() - downRawY;

                        return true;

                    case MotionEvent.ACTION_UP:

                        float upRawX = event.getRawX();
                        float upRawY = event.getRawY();

                        float upDX = upRawX - downRawX;
                        float upDY = upRawY - downRawY;
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        params.x = initialX + (int) (event.getRawX() - initialTouchX);
                        params.y = initialY + (int) (event.getRawY() - initialTouchY);
                        mWindowManager.updateViewLayout(mFloatingView, params);
                        return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
AndroidManifest.xml  file and update your service declarations under the application tag. Also, add  FOREGROUND_SERVICE, INTERNET and  WAKE_LOCK .Make sure you don't forget to include them as they won't work otherwise.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="com.example.endless">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

        <service
                android:name=".FloatingViewService"
                android:enabled="true"
                android:exported="false">
        </service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

You can use the following code to check if the service is running. If the service is already in running mode, it does not need to be restarted otherwise start in your MainActivity.

FloatingViewService mFloatingService = new FloatingViewService(getApplicationContext());
  Intent mServiceIntent = new Intent(getApplicationContext(), mFloatingService.getClass());
if (!isMyServiceRunning(mFloatingService.getClass())) {
    startService(mServiceIntent);
}

Method isMyServiceRunning() is below add this in your MainActivity.

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            Log.i ("isMyServiceRunning?", true+"");
            return true;
        }
    }
    Log.i ("isMyServiceRunning?", false+"");
    return false;
}
Then Create a Floating Widget design. Create File floating_layout.xml Like This

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/rl_close_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/relativeLayoutParent"
            android:layout_width="80dp"
            android:layout_height="70dp">

            <RelativeLayout
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:background="@drawable/floating_round_main_shape">

                <RelativeLayout
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_centerInParent="true"
                    android:background="@drawable/floating_inner_round_shape">

                    <ImageView
                        android:layout_width="25dp"
                        android:layout_height="25dp"
                        android:layout_centerInParent="true"
                        android:src="@drawable/ic_voice_icon" />

                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

I hope it will help these services. 
Note:-This service will run better in Oreo and above versions.


October 04, 20203 minutesauthorVivek Beladiya