Android

Android three ways to set click listener

In Android we can set click listener by three ways

  1. Setting individual click listener for each element.
  2. Implementing OnClickListener in activity level.
  3. Creating a separate function for handling button click and add this function in xml

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:orientation="vertical"
    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.bm.buttonclickeg.MainActivity">

    <Button
        android:id="@+id/btn_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/btn_two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2" />

    <Button
        android:id="@+id/btn_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myBtnClick"
        android:text="Button 3" />

</LinearLayout>

In the above example btn_three I have added a property android:onClick=”myBtnClick” myBtnClick is a function I have defined in activiy

MainActivity.java

package com.example.bm.buttonclickeg;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        //option 1
        
        Button btn1 = (Button) findViewById(R.id.btn_one);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(MainActivity.this, "Created individual click listener", Toast.LENGTH_SHORT).show();
            }
        });


        //option 2
        Button btn2 = (Button) findViewById(R.id.btn_two);

        btn2.setOnClickListener(this);

    }


    //option 2
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_two:
                Toast.makeText(MainActivity.this, "Implemented click listener in activity", Toast.LENGTH_SHORT).show();
                break;
        }

    }


    //option 3
    // This function I have added in the btn_tree xml
    public void myBtnClick(View v) {
        Toast.makeText(MainActivity.this, "Created a separate function for handling button click and added this function in button xml", Toast.LENGTH_SHORT).show();
    }
}

 

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

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 Intent Service

Intent Service Class sample

public class MyIntentService extends IntentService {

    public static final String Somevariables = "somevalue";

    public MyIntentService() {

        super(MyIntentService.class.getName()); // you can give any string but it is good practice to giving classname
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //--some code --
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        
        //you can retrive intent extras
        String msg = intent.getStringExtra(EXTRA_KEY);

        //--actual backgroung code gos here  --
    }
}

Add service in manifest also

<service android:name=".MyIntentService"/>

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

By bm on June 3, 2016 | Android | A comment?
Tags: ,