Android的Service与Activity通信

受益于从图书馆借过来的书,今天再学习了Android的Service与Activity的通信,特列出如下代码:

 

main.xml 文件内容如下:

<?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"
    >
<TextView  android:id = "@+id/text"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:text="startservice" 
android:id="@+id/Button01" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<Button android:text="stopservice" 
android:id="@+id/Button02" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<Button android:text="bindservice" 
android:id="@+id/Button03" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<Button android:text="unbindservice" 
android:id="@+id/Button04" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
</LinearLayout>

 

AndroidManifest.xml文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.demo.myServiceComm"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".myServiceComm"
                  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>


</manifest> 


 

MyService.java文件内容如下:

package com.demo.myServiceComm;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

public class MyService extends Service {

	//定义一个TAG标签
	private static final String TAG = "MyService";
	
	//这里定义一个Binder类,用在onBind()方法里。
	//这样Activity那边可以获取得到
	private MyBinder mBinder = new MyBinder();
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Log.e(TAG,"start IBinder~~~");
		return mBinder;
	}
	
	//当服务第一次创建时调用该方法
	public void onCreate(){
		Log.d(TAG,"onCreate~~~");
		super.onCreate();
	}
	
	//当服务销毁时调用该方法
	public void onDestroy(){
		Log.d(TAG,"onDestroy~~~");
		super.onDestroy();
	}
	
	//当服务开始时调用该方法
	public void onStart(Intent intent,int startId){
		Log.d(TAG,"onStart~~~!");
		super.onStart(intent,startId);
	}
	
	//
	public boolean onUnbind(Intent intent){
		Log.e(TAG, "start onUnbind~~~");
		return super.onUnbind(intent);
	}

	//获取当前系统时间函数
	public String getSystemTime(){
		Time t = new Time();
		t.setToNow();
		t.format3339(true);
		return t.toString();
	}
	
	public class MyBinder extends Binder{
		MyService getService(){
			return MyService.this;
		}
	}
}


 

myServiceComm.java文件内容如下:

package com.demo.myServiceComm;

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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class myServiceComm extends Activity {
	
	private MyService mMyService;
	private TextView mTextView;
	private Button startserviceBtn;
	private Button stopserviceBtn;
	private Button bindserviceBtn;
	private Button unbindserviceBtn;
	
	//定义上下文对象
	private Context mContext;
	
	private ServiceConnection mServiceConnection = new ServiceConnection()
	{

		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mMyService = ((MyService.MyBinder)service).getService();
			mTextView.setText("I am frome service :"
					+ mMyService.getSystemTime());
		}

		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}
		
	};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupViews();
    }
    
    public void setupViews()
    {
    	mContext = this;
    	
    	//元素绑定
    	mTextView = (TextView)findViewById(R.id.text);
    	startserviceBtn = (Button)findViewById(R.id.Button01);
    	stopserviceBtn = (Button)findViewById(R.id.Button02);
    	bindserviceBtn = (Button)findViewById(R.id.Button03);
    	unbindserviceBtn = (Button)findViewById(R.id.Button04);
    	
    	//新建service意图
    	final Intent serviceIntent = new Intent(this,MyService.class);
    	
    	//添加监听接口以及消息处理函数
    	startserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//打开服务
				mContext.startService(serviceIntent);
			}
    	});
    	
    	stopserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//停止服务
				mContext.stopService(serviceIntent);
			}
    	});
    	
    	bindserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//绑定服务
				mContext.bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
			}
    	});
    	
    	unbindserviceBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//撤销绑定服务
				mContext.unbindService(mServiceConnection);
			}
    		
    	});
    }
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值