ServicesDemo - Using Android Services

转载 2012年03月21日 17:42:32
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
http://marakana.com/static/tutorials/ServicesDemo.zip

Music File
http://marakana.com/static/tutorials/braincandy.m4a

Walkthrough: Developing a Custom Application Using Excel Web Services

  Walkthrough: Developing a Custom Application Using Excel Web Services SharePoint 2010 Other Ver...

Spring 框架参考文档(六)-Integration之Remoting and web services using Spring

Spring 框架参考文档(五)-The Web之WebSocket 支持 Part VI. Integration This part of the reference do...

How to write RESTful web services using spring 3 mvc

Step 1) Update pom.xml to add support of JAXB and Jackson (for xml and json formats). org.codehaus...
  • gmemai
  • gmemai
  • 2015年08月31日 17:27
  • 321

Using SharePoint Web Services to Fill Out an InfoPath Form

Problem When filling out forms users tend to use nicknames, initials, or non-given names to repres...

Using Business Connectivity Services in SharePoint 2010

Kirk Evans One of my kids’ favorite books is called If You Give a Mouse a Cookie by Laura Numeroff─...

论文阅读——译文:Enhancing Dynamic Cloud-based Services using Network Virtualization

Enhancing Dynamic Cloud-based Services using Network Virtualization 使用网络虚拟化来提高动态的基于云的服务 摘要: 据说未来服...

Connecting Docker for Cloud Services using SDN and Network Virtualization

Abstract Theexplosive scale of container CPUs needs highly efficient network virtualization Chal...

Designing Data Storage Architecture-Using the Windows Azure Storage Services

http://msdn.microsoft.com/en-us/library/ee924681.aspx The Windows Azure storage services provide ...

Apps using background location services must provide a reason that clarifies the purpose of the use

上架App Store被拒 原因:  Apps using background location services must provide a reason that clarifies th...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:ServicesDemo - Using Android Services
举报原因:
原因补充:

(最多只允许输入30个字)