Android service实例

本文详细介绍了如何使用Java创建服务并实现远程调用,包括创建服务类、生成AIDL文件、打包为jar包、修改manifest文件以及客户端如何连接和服务交互的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[/code]首先继承Service
[code="java"]
package com.tcl.kang.demo;

import com.tcl.kang.demo.ICountService;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class MyService extends Service
{


@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}


private ICountService.Stub myBinder = new ICountService.Stub()
{
@Override
public int getCount() throws RemoteException
{
// TODO Auto-generated method stub
return 0;
}
};

@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stubk
return myBinder;
}

}



创建一个aidl文件 ICountService.aidl,这时会在gen目录下生成一个java文件,将java文件打包成jar。

package com.tcl.kang.demo;

interface ICountService
{
int getCount();
}


修改manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tcl.kang.demo" android:versionCode="1"
android:versionName="1.0">
<application>
<service android:name=".MyService">
<intent-filter>
<action android:name="com.tcl.kang.demo.MyService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
<uses-sdk android:minSdkVersion="8" />

</manifest>


客户端:首先包含刚才的jar包,


package com.tcl.testservice2;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.tcl.kang.demo.ICountService;

public class TestService2Activity extends Activity {
private ICountService countService;
private ServiceConnection myConnection = new ServiceConnection()
{

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
countService = (ICountService.Stub.asInterface(service));
try {
Log.v("", "kang: count="+countService.getCount());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
countService = null;
}

};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent("com.tcl.kang.demo.MyService"),myConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unbindService(myConnection);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值