Android Remote Service

转自http://blog.csdn.net/u0fly/article/details/5907362,并补充了main.xml文件

src
    └── com
        └── fly
            ├── IRemoteService.aidl
            ├── RemoteServiceActivity.java
            └── RemoteService.java

 

IRemoteService.aidl

package com.fly;
interface IRemoteService {
	int getCount();
}

 

RemoteServiceActivity.java

package com.fly;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
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 android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class RemoteServiceActivity extends Activity {
	private static final String TAG = "U0fly RemoteServiceActivity";
	private Button bnStart, bnStop;
	private TextView text1;
	private int count;
	private boolean isBound;
	
	private ServiceConnection serviceConnection = new ServiceConnection() {
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Log.d(TAG, "Start on Service Connected now");
			remoteService = IRemoteService.Stub.asInterface(service);
			try {
				Log.d(TAG, "on serivce connected, count is "
						+ remoteService.getCount());
			} catch (RemoteException e) {
				throw new RuntimeException(e);
			}
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Log.d(TAG, "Start on Service Disconnected now");
			remoteService = null;
		}
	};
	private IRemoteService remoteService;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		this.bindService(new Intent(RemoteServiceActivity.this, RemoteService.class),
				this.serviceConnection, Context.BIND_AUTO_CREATE);
		Log.d(TAG, "Bind Service now");
		isBound = true;
		
		initUi();
		Log.d(TAG, "Init UI now");
		bnStart.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				
				try {
					text1.setText("Start Service now! count is :" + remoteService.getCount());
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				startService(new Intent(RemoteServiceActivity.this, RemoteService.class));
				Log.d(TAG, "Start Service now");
				
			}
		});
		bnStop.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				text1.setText("Stop Service now!");
				stopService(new Intent(RemoteServiceActivity.this, RemoteService.class));
				Log.d(TAG, "Stop Service now");
			}
		});
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "============> onDestroy");
		if (isBound) {
			this.unbindService(serviceConnection);
			isBound = false;
		}
	}
	public void initUi() {
		bnStart = (Button) findViewById(R.id.BnStart);
		bnStop = (Button) findViewById(R.id.BnStop);
		text1 = (TextView) findViewById(R.id.text1);
	}
}

RemoteService.java

package com.fly;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class RemoteService extends Service {
	private static final String TAG = "U0fly RemoteService";
	private int count;
	private boolean threadDisable;
	private IRemoteService.Stub serviceBinder = new IRemoteService.Stub() {
		@Override
		public int getCount() throws RemoteException {
			// TODO Auto-generated method stub
			return count;
		}
	};
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(TAG, "============>  onBind");
		return serviceBinder;
	}
	@Override
	public boolean onUnbind(Intent i) {
		Log.e(TAG, "============>  onUnbind");
		return false;
	}
	@Override
	public void onRebind(Intent i) {
		Log.e(TAG, "============>  onRebind");
	}
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "============>  onCreate");
		 //TODO
		 new Thread(new Runnable() {
		
		 @Override
		 public void run() {
		
		 while (!threadDisable) {
		 try {
		 Thread.sleep(1000);
		 } catch (InterruptedException e) {
		 }
		 count++;
		 Log.d(TAG, "Count is " + count);
		 }
		 }
		 }).start();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		Log.d(TAG, "============> onStart");
/*
		// TODO
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (!threadDisable) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
					count++;
					Log.d(TAG, "Count is " + count);
				}
			}
		}).start();*/
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		// TODO
		this.threadDisable = true;
		Log.d(TAG, "============>  ondestroy");
	}
	public int getCount() {
		return count;
	}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.fly" android:versionCode="1" android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".RemoteServiceActivity"
			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:name="RemoteService">
			<intent-fliter>
				<action android:name="com.fly.RemoteService" />
			</intent-fliter>
		</service>
	</application>
	<uses-sdk android:minSdkVersion="7" />
</manifest> 


main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

    <Button
        android:id="@+id/BnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="BnStart" />

    <Button
        android:id="@+id/BnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="BnStop" />

</RelativeLayout>



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值