首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

Android SERVICE(详解2 Bindservice)

2012-09-10 
Android SERVICE(详解二 Bindservice)---------------------------------Main.javapackage com.example.se

Android SERVICE(详解二 Bindservice)

---------------------------------Main.java
package com.example.service2;


import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;


public class MainActivity extends Activity {



private CountService countservice;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("Main", "in");
        Intent intent=new Intent(MainActivity.this,CountService.class);
        bindService(intent , conn, Context.BIND_AUTO_CREATE);
    }


    @Override
    protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    this.unbindService(conn);
    Log.v("Main", "out");
    }
    private ServiceConnection conn=new ServiceConnection() {




public void onServiceConnected(
ComponentName name,
IBinder service) {
// TODO Auto-generated method stub
countservice=((CountService.ServiceBinder)service).getService();

}


public void onServiceDisconnected(
ComponentName name) {
// TODO Auto-generated method stub


countservice=null;

}
};
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


---------------.java2
package com.example.service2;


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


public class CountService extends
Service {
boolean Disable;
int count;
ServiceBinder servicebinder;


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

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

public void run() {
// TODO Auto-generated method stub




while (!Disable) {
try {
Thread.sleep(1000);
}
catch (Exception e) {
// TODO: handle exception
}


count++;
Log.v("总数", "总数是"+count);
}
}
}).start();
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.Disable=true;
}


class ServiceBinder extends Binder {


public CountService getService() {
return CountService.this;


}
}






--------------MANIFERST加上 service name.

热点排行