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

导入项目到android studio中遇到的各种问题

最近学习一下别人的源码,于是在网上下载了各种源码,有17年的16年的等,本来是想直接找一个androidstudio项目,看着这些年份相对13年(Androidstudio问世)比较久远,猜想这些应该...
  • Cdaimadada
  • Cdaimadada
  • 2018年01月12日 09:46
  • 117

WEB SERVICE

 Writing a Web Service in .NET using VS .NET very is easy. However, it is possible to write Web Serv...
  • yuanxi
  • yuanxi
  • 2008年02月24日 22:44
  • 425

Location-Based Services Using CellID in Android

Location-Based Services Using CellID in Android               ---"基于基站CellID信息的定位" 顾名思义,就是没有GPS功...
  • thinkinhex
  • thinkinhex
  • 2012年08月22日 14:44
  • 1137

zookeeper安装与注意

注意先安装jdk,并配置好,否则会报出Error contacting service. It is probably not running 另:查找原因在zookeeper.out打开查看 ...
  • luozhonghua2014
  • luozhonghua2014
  • 2017年03月04日 23:18
  • 378

在Linux环境安装 zookeeper

在 CentOS7 上安装 zookeeper-3.4.9 服务  1、创建 /usr/local/services/zookeeper 文件夹:     mkdir -p /usr/local/s...
  • u011730649
  • u011730649
  • 2017年07月17日 15:34
  • 139

Using Web Services Effectively

  1.1 Web Service Processing and Interaction Models Before you even begin to design a...
  • narci
  • narci
  • 2006年06月12日 22:38
  • 1453

Using Windows Web Services

Using Windows Web Services http://msdn.microsoft.com/en-us/library/dd430462(v=vs.85).aspx
  • dove1980
  • dove1980
  • 2014年01月06日 18:12
  • 423

Using gsoap for web services

http://wiki.forum.nokia.com/index.php/Using_gsoap_for_web_services
  • l270378034
  • l270378034
  • 2011年02月17日 10:10
  • 810

Android Google Services Framework & Google Play

今天早上看到手机提示系统更新完成,需要重启,然后点击了reboot, 没想到重启后google play 打不开了,并且老是提 has topped。重新安装以前存储的 google services...
  • lanmo555
  • lanmo555
  • 2016年04月16日 01:43
  • 1877

Android Services简介

文件 描述 class AlarmManagerService extends IAlarmManager.Stub { //定时管理服务 public class AppOp...
  • koumen3
  • koumen3
  • 2016年03月14日 16:00
  • 1558
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:ServicesDemo - Using Android Services
举报原因:
原因补充:

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