Android service sample (2015.12.3)


http://www.tutorialspoint.com/android/android_services.htm 


1. 新建一个service文件:MyService.java

package com.example.helloworld;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
	   
	@Override
	public IBinder onBind(Intent arg0)	{
		return null;		
	}
	
	@Override 
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
	}
	
}

2. 在Manifest.xml中声明:

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

3. 修改界面文件:增加2个buttong, 来启动和停止 service

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="68dp"
        android:text="Start Service" 
        <span style="color:#ff0000;">android:onClick="startService" /></span>

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:text="Stop Service" 
        <span style="color:#ff0000;">android:onClick="stopService"/></span>


Android Service Demo


4. 在界面xml中调用的两个函数:定义在MainActivity.java中

    //Method to start the service
    public void startService(View view) {
    	startService(new Intent(getBaseContext(), MyService.class));
    }
    
    public void stopService(View view) {
    	stopService(new Intent(getBaseContext(), MyService.class));
    }


编译,运行。


多体会下面的切换过程:


Android Service lifecycle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值