domingo, 28 de octubre de 2012

How to check if a service is running?


Problem:

Need to check if some service is running.


Solution:

Create a method as the following


private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.MyService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;

Using Android Services (Running app in background)



How to run an application in background?

To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service. 



context.startService() | ->onCreate() - >onStartCommand() [service running]

Calling the applications stopService() method to stop the service. 

context.stopService() | ->onDestroy() [service stops]

Something that we didn't use in this example is bindService() which just calls the services onCreate() method but does not call the onStartCommand(). onBindService() is used to create persistance connection to the service.

context.onBindService() | ->onCreate() [service created]

This Services Demo is simple as it plays a audio file and by listening to click events of the buttons invokes the MyService service. 

ServicesDemo.java

Code:
package com.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesDemo extends Activity implements OnClickListener {
  private static final String TAG = "ServicesDemo";
  Button buttonStart, buttonStop;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, MyService.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, MyService.class));
      break;
    }
  }
}

To understand the audiomedia player, please review the AudioDemo posted in this form. The custom MyService extends Service class and necessary to override various methods of its lifecycle ie onCreate(), onStartCommand(), or onDestroy()

MyService.java
Code:
package com.example;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
 private static final String TAG = "MyService";
 MediaPlayer player;
 
 @Override
 public IBinder onBind(Intent intent) {
  return null;
 }
 
 @Override
 public void onCreate() {
  Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
  Log.d(TAG, "onCreate");
  
  player = MediaPlayer.create(this, R.raw.braincandy);
  player.setLooping(false); // Set looping
 }

 @Override
 public void onDestroy() {
  Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
  Log.d(TAG, "onDestroy");
  player.stop();
 }
 
 @Override
 public void onStart(Intent intent, int startid) {
  Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
  Log.d(TAG, "onStart");
  player.start();
 }
}

Necessary to let the AndroidManifest file know about your service <service android:enabled="true" android:name=".MyService" />

AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ServicesDemo" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <service android:enabled="true" android:name=".MyService" />
  </application>
  <uses-sdk android:minSdkVersion="3" />
</manifest> 

main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="Services Demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="Start"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:id="@+id/buttonStop"></Button>
</LinearLayout>

Output


source: Marakana



sábado, 27 de octubre de 2012

How to make Android Vibrate?


This is an example of how to make vibration with Android

Making Android phones vibrate is a good way to provide haptic feedback to users or to interact with users even when phone volume is low. This can ensure a better user experience and therefore increase the perceived integrity of your Android application.

The Vibrator Documentation describes the interface for making an Android phone vibrate. With this interface, you can cause an Android phone to vibrate in one of the following ways:

Vibrate for a given length of time
Vibrate in a given pattern
Vibrate repeatedly until cancelled
Below are examples of these three vibrating methods.

IMPORTANT: First, Grant Vibration Permissions
Before you start adding the code necessary to cause your application to vibrate, you must first notify Android that your application expects to have permission to use the Vibrator. If you do not do this, you will receive a Force Close. Nobody likes encountering a Force Close; Do not forget this important first step!

Add the uses-permission line to your Manifest.xml file, outside of the block.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
    <uses-permission android:name="android.permission.VIBRATE"/>
    <application android:label="...">
        ...
    </application>
</manifest>


Example 1: Vibrate for a Given Length of Time

This example is useful when a user touches your application and you would like to provide haptic feedback. This is the simplest method of vibration. I like 50 milliseconds as a good single-touch-feedback vibrate. You can experiment with different lengths (on your physical phone) to decide how long to make your vibration.

WARNING: This code must be called with a reference to a Context

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 300 milliseconds
v.vibrate(300);

Example 2: Vibrate in a Given Pattern

This method of vibration is useful when you need to provide a user with a one-time notification, such as receiving a text message. In this example, I have created a one-time vibration notification in the Morse Code SOS pattern.

WARNING: This code must be called with a reference to a Context

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// This example will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
int dot = 200;      // Length of a Morse Code "dot" in milliseconds
int dash = 500;     // Length of a Morse Code "dash" in milliseconds
int short_gap = 200;    // Length of Gap Between dots/dashes
int medium_gap = 500;   // Length of Gap Between Letters
int long_gap = 1000;    // Length of Gap Between Words
long[] pattern = {
    0,  // Start immediately
    dot, short_gap, dot, short_gap, dot,    // s
    medium_gap,
    dash, short_gap, dash, short_gap, dash, // o
    medium_gap,
    dot, short_gap, dot, short_gap, dot,    // s
    long_gap
};

// Only perform this pattern one time (-1 means "do not repeat")
v.vibrate(pattern, -1);

Example 3: Vibrate Repeatedly Until Cancelled

This method of vibration is useful when you need to notify the user of something that requires more immediate action, such as an incoming phone call. You can repeat a given pattern until the Vibrator is cancelled, either by the system or manually by your Android application.

WARNING: The below example will cease vibrating when the screen times out.
WARNING: This code must be called with a reference to a Context

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start immediately
// Vibrate for 200 milliseconds
// Sleep for 500 milliseconds
long[] pattern = { 0, 200, 500 };

// The "0" means to repeat the pattern starting at the beginning
//  WARNING : If you start at the wrong index (e.g., 1) then your pattern will be off --
// You will vibrate for your pause times and pause for your vibrate times !
v.vibrate(pattern, 0);
In another part of your code, you can handle turning off the vibrator as shown below:

view sourceprint?
// Stop the Vibrator in the middle of whatever it is doing
//  WARNING : Do *not* do this immediately after calling .vibrate().
// Otherwise, it may not have time to even begin vibrating!
v.cancel();

Source: Android | Konreu

viernes, 26 de octubre de 2012

How to add two edit text fields in an alert dialog?



Problem:

Need to put a TextView into an AlertBox

Solution:

Put the following code into Java class


    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    alert.show(); 

source: StackOverflow

jueves, 25 de octubre de 2012

How do I make links in a TextView clickable?



Problem:

I need to put anchor html code into a textview and make it clickable in the android application.

Solution:

This goes in the Java code


    // text2 has links specified by putting <a> tags in the string
    // resource.  By default these links will appear but not
    // respond to user input.  To make them active, you need to
    // call setMovementMethod() on the TextView object.

    TextView t2 = (TextView) findViewById(R.id.text2);
    t2.setMovementMethod(LinkMovementMethod.getInstance());



This goes into the xml view


<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/txtCredits"
    android:id="@+id/infoTxtCredits"
    android:layout_below="@+id/imgCredits" android:layout_centerInParent="true"
    android:layout_marginTop="20dp"></TextView>

miércoles, 24 de octubre de 2012

Closing Application with Exit button



Closing Application with Exit button. How to?

Sometimes we need to add a button the ability to close the current Activity (View). For doing that is the following code. Put that into an "onCreate" event and that is all...



this.close_Button = (Button)this.findViewById(R.id.close);
   this.close_Button.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
        finish();
     }
  });

miércoles, 17 de octubre de 2012

Add Google Admob in Android Application


What is Admob?

Admob is a new way to monetize mobile applications. Currently, it supports multi-platform, including iPhone, Android, WebOS, and Flash Lite. In this AdMob for Android example, I will show you how to integrate Admob in your android applications defined in layout XML file.

First of all, we need to go to the Admob website to register an account, in order to get the Admod account ID. Then, let’s go the google code to download the latest Google AdMob Ads SDK for android. You also can get download it from your admob “Sites & Apps” setting page. After we get the AdMob SDK, we need to add the AdMob sdk jar in our android project. For those who want to implement the AdMob in Android Java code, you can copy the Jar file in the project and include it in your android project Build path. For more details, please refer the post Add AdMob v6.0 to Android Apps. If you want to layout the AdView in layout xml file, you need to add jar file in the /libs/ folder under your android project.
AdMob Build Path
AdMob Build Path

1. For Admob, it’s better to add the com.google.ads.AdActivity in your Manifest.xml file. And don’t forget to add the user permission for it. Below is my mainfest.xml example.

?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jms.AdmobExample"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AdmobExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.google.ads.AdActivity"                    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
    </application>

  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</manifest>

2. The basic class in android applications are composed of View objects. For Admob, we need use AdView class which is provided in the SDK jar file. Actually, it will be put into the main layout file, it’s easy for you to build your own layout. Let’s see my main.xml:
?
<?xml version="1.0" encoding="utf-8"?>
<linearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<imageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/a"
    />

<com.google.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:id="@+id/adView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    ads:adSize="BANNER"
    ads:adUnitId="Your Admob ID"
/>
</linearLayout>

3. Send AdMob AdRequest in your Activity class:

AdView adview = (AdView)findViewById(R.id.adView);
AdRequest re = new AdRequest();
re.setTesting(true);
adview.loadAd(re);

There are a most important things you need to know:
At the first time, the Admob Ads will take 1 or 2 minutes to show.
In the simulator, I never try it successfully. I always get the time out error. I only try it in my HTC Desire, and it really works.
Some times, it will show no ads to show. It’s not the problem, because it really doesn’t have ads to show for some situations.
Compile Errors Solutions
One common compiling error is “Error inflating class com.google.ads.AdView”. The error message is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jms/com.jms.InfiniteGalleryActivity}: android.view.InflateException: Binary XML file line #17: Error inflating class com.google.ads.AdView
This is one of the compile errors which many android programmers meet with. The solution is creating the /libs folder under your android project root folder and putting the AdMob Jar file inside.

AdMob Build Path

Another compiling error is “Required XML attribute missing”. The error message is:
Could not initialize AdView: Required XML attribute “adSize” missing
This is because the Android can not find the AdSize defination. It can be solved by specifying the right ads name spacing in the layout xml:
?
xmlns:ads="http://schemas.android.com/apk/libs/com.google.ads"

Source: http://jmsliu.com/209/add-google-admob-in-android-application.html