Android execute code after delay

Android execute code after delay

In this sample code the myFuction() will call after 10 second

new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

          //your code here
          //you can add a block of code or a function cll

          myFunction();

        }
    }, 10000);  //setting 10 second delay : 1000 = 1 second

 

don't use Thread.sleep(10000);  because it will block your UI

By bm on July 20, 2016 | Android | 1 comment
Tags: , ,

Android check service is running or not

Android check service is running or not

Function 1

In this function, we can pass class as parameter

Definition

    /**
     *  check the given service is running
     * @param serviceClass class eg MyService.class
     * @return boolean
     */
    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())) {
                return true;
            }
        }
        return false;
    }

Function call

isMyServiceRunning(MyService.class);

Function 2

Here we can pass the class name with the package name

Definition

    /**
     *  check the given service is running
     * @param serviceClassname this shoul be the service class name with the package eg "com.example.eg.intentserviceexample.MyService"
     * @return boolean 
     */
    private boolean isMyServiceRunning(String serviceClassname) {

        //getting all the services
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {

            Log.i("debug", service.service.getClassName());

            if (serviceClassname.equals(service.service.getClassName())) {

                return true;
            }
        }
        return false;
    }

 

calling the function

isMyServiceRunning("com.example.eg.intentserviceexample.MyService");

 

Simple intent service example click the link https://wiki.workassis.com/android-intentservice-example

By bm on July 19, 2016 | Android | A comment?
Tags: ,

Android Intent Service Example

Simple example for Android Intent Service and broadcast receiver

Declaring Service in the Manifest

AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <service
            android:name=".MyService"
            android:exported="false"/>



    </application>

</manifest>

android:exported :- Whether or not components of other applications can invoke the service or interact with it — “true” if they can, and “false” if not. When the value is “false“, only components of the same application or applications with the same user ID can start the service or bind to it. – developer.android.com

More about service tag click here

MainActivity.java

package com.example.eg.intentserviceexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        //setting button click
        findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Creating an intent for sending to service
                Intent intent = new Intent(getApplicationContext(), MyService.class);

                intent.putExtra("id", 101);
                intent.putExtra("msg", "hi");

                //starting service
                startService(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        //register broadcast receiver for the intent MyTaskStatus
        LocalBroadcastManager.getInstance(this).registerReceiver(MyReceiver, new IntentFilter("MyServiceStatus"));
    }


    //Defining broadcast receiver
    private BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String message = intent.getStringExtra("serviceMessage");

            Toast.makeText(MainActivity.this, "Received : " + message, Toast.LENGTH_SHORT).show();
        }
    };


    @Override
    protected void onStop() {
        super.onStop();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(MyReceiver);
    }

}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.eg.intentserviceexample.MainActivity"
    android:orientation="vertical">


    <Button
        android:id="@+id/btn_start_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"/>


</LinearLayout>

MyService.java

package com.example.eg.intentserviceexample;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class MyService extends IntentService {

    public MyService() {
        super(MyService.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {


        //retrieving data from the received intent
        int id = intent.getIntExtra("id",0);
        String message = intent.getStringExtra("msg");

        Log.i("Data  ", "id : "+id+" message : "+ message );
        //-----------------------------------------------


        //Do your long running task here


        //------------------------------------------------

        //Broadcasting some data
        Intent myIntent = new Intent("MyServiceStatus");
        myIntent.putExtra("serviceMessage", "Task done");

        // Send broadcast
        LocalBroadcastManager.getInstance(this).sendBroadcast(myIntent);

    }
}

 

For How to check the service is running click the link : https://wiki.workassis.com/android-check-the-service-is-running

 

ref:

https://developer.android.com/reference/android/app/IntentService.html

https://developer.android.com/training/run-background-service/create-service.html

https://developer.android.com/guide/topics/manifest/service-element.html

Android Local Broadcast Receiver

Simple Local broadcast receiver example

MainActivity

package com.example.eg.localbroadcastreciver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        // adding click event for the button
        findViewById(R.id.send_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //the following code will be inside your service
                //creating intent MyTaskStatus
                Intent myIntent = new Intent("MyTaskStatus");
                myIntent.putExtra("MyMessage", "Hi");

                // Send broadcast
                LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(myIntent);

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

        //register broadcast receiver for the intent MyTaskStatus
        LocalBroadcastManager.getInstance(this).registerReceiver(MyReceiver, new IntentFilter("MyTaskStatus"));

    }

    //Defining broadcast receiver
    private BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String message = intent.getStringExtra("MyMessage");

            Toast.makeText(MainActivity.this, "Received : "+message, Toast.LENGTH_SHORT).show();
        }
    };



    @Override
    protected void onStop() {
        super.onStop();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(MyReceiver);
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.eg.localbroadcastreciver.MainActivity"
    android:orientation="vertical">


    <Button
        android:id="@+id/send_broadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"/>


</LinearLayout>

 

————————————————————————————————————————————————————–

Another exaple

Here registering the broadcast receiver with the action

package com.example.eg.localbroadcastreciver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {

    public static final String ACTION_DONE = "MyTaskService#ACTION_DONE";

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

        // adding click event for the button
        findViewById(R.id.send_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //the following code will be inside your service
                // Create Intent to broadcast the task information.
                Intent intent = new Intent();
                intent.setAction(ACTION_DONE);
                intent.putExtra("msg", "Hi");

                // Send local broadcast, running Activities will be notified about the task.
                LocalBroadcastManager manager = LocalBroadcastManager.getInstance(Main2Activity.this);
                manager.sendBroadcast(intent);

            }
        });

    }

    // BroadcastReceiver to get information from MyTaskService about task completion.
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //no need to check action again
            //if (intent.getAction().equals(ACTION_DONE)) {

            String msg = intent.getStringExtra("msg");

            Toast.makeText(context,"Broadcast received message : "+ msg, Toast.LENGTH_SHORT).show();
            //}
        }
    };

    @Override
    public void onStart() {
        super.onStart();

        //registering intent filter based on action
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DONE);

        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
        manager.registerReceiver(mReceiver, filter);
    }



    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

}

activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.eg.localbroadcastreciver.Main2Activity">

    <Button
        android:id="@+id/send_broadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"/>

</RelativeLayout>

 

 

ref: https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

By bm on July 13, 2016 | Android | A comment?

Android AsyncTask

“AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.” – developer.android

Async task class definition

class AsyncTaskClassName extends AsyncTask<argumentType, progrssValueType, taskResultType> {

     //inputarg can contain array of values
     protected taskResultType doInBackground(argumentType... inputarg) {

         //-------
         //-- Your Long running task here ----

         int count = inputarg.length;

         for (int i = 0; i < count; i++) {
             Log.i("from Async task", inputarg[i] );
         }

         //-------

         publishProgress(progrssValue));


         return taskresult;
     }

     protected void onProgressUpdate(progrssValueType... progress) {

         //update the progress
         setProgressPercent(progress[0]);

     }
     
     //this will call after finishing the doInBackground function
     protected void onPostExecute(taskResultType result) {

         // Update the ui elements 
         //show some notification
         showDialog("Task done "+ result);

     }
 }

starting task

new AsyncTaskClassName().execute(arg1, arg2, etc );

 

Or we can execute directly

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... params) {
        //long running task
        return null ;
    }


    @Override
    protected void onPostExecute(Void x) {
        //update the ui elemets
    }
}.execute();

 

 

ref : https://developer.android.com/reference/android/os/AsyncTask.html

By bm on | Android | 3 comments

Google apps catchall email settings

In this video we are explaining how to configure the catch all email in google apps

By bm on July 8, 2016 | Google | A comment?

Ajax
Android
Android XML
ArrayList
Browser
Codeigniter
Css
Drupal 8