当前位置: 代码迷 >> Android >> Android service范例
  详细解决方案

Android service范例

热度:108   发布时间:2016-05-01 14:04:51.0
Android service实例
首先继承Service
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);	}    }
  相关解决方案