展会信息港展会大全

Android建立能与Activity进行相互通信的本地服务
来源:互联网   发布日期:2016-01-14 10:44:38   浏览:1820次  

导读:MyService.java[java] 瀀愀挀欀愀最攀 cn.itcast.service; 椀洀瀀漀爀琀 android.app.Service; 椀洀瀀漀爀琀 and...

MyService.java

[java]

package cn.itcast.service;

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

public class MyService extends Service {

private Binder binder = new MyBinder();

public String getName(int id){

return "传智播客";

}

@Override

public IBinder onBind(Intent intent) {

return binder;

}

private final class MyBinder extends Binder implements IService{

public String getName(int id){

return MyService.this.getName(23);

}

}

}

MainActivity.java

[java]

package cn.itcast.service;

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.view.View;

import android.widget.Button;

import android.widget.TextView;

public class MainActivity extends Activity {

private MyServiceConnection conn;

private IService myservice;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

conn = new MyServiceConnection();

Intent intent = new Intent(this, MyService.class);

bindService(intent, conn, BIND_AUTO_CREATE);

Button button = (Button) this.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

TextView resultView = (TextView) findViewById(R.id.result);

resultView.setText(myservice.getName(56));

}

});

}

private final class MyServiceConnection implements ServiceConnection{

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

myservice = (IService)service;

}

@Override

public void onServiceDisconnected(ComponentName name) {

myservice = null;

}

}

@Override

protected void onDestroy() {

unbindService(conn);

super.onDestroy();

}

}

IService.java

[java]

package cn.itcast.service;

public interface IService {

public String getName(int id);

}

[html]

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="cn.itcast.service"

android:versionCode="1"

android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".MainActivity"

android:label="@string/app_name">

<intent-filter>www.2cto.com

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

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

</application>

<uses-sdk android:minSdkVersion="8" />

</manifest>

赞助本站

人工智能实验室

相关热词: android开发 教程

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港