activity启动service的两种方式

时间:2022-08-17 16:44:03

1.startService()
2.onbind()

1.测试主页面


package com.example.lab4;

import android.os.Bundle;

import com.example.model.Book;
import com.example.service.BookService;

import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btn1 = (Button)findViewById(R.id.btn1);
Button btn2 = (Button)findViewById(R.id.btn2);
Button btn3 = (Button)findViewById(R.id.btn3);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//通过start启动
Toast.makeText(MainActivity.this, "fdsfsd", 1000).show();
Intent intent = new Intent(MainActivity.this,BookService.class);
Book book = new Book ();
book.setBookname("陈世滔的书");
book.setAuthor("陈世滔");
intent.putExtra("book", book);
startService(intent);
}
});

btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,BookService.class);
stopService(intent);
}
});

btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,GetServiceActivity.class);
startActivity(intent);
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

2.从主页面中启动activity2并将其与service绑定

package com.example.lab4;

import com.example.model.Book;
import com.example.service.BookService;

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.Menu;
import android.widget.TextView;

public class GetServiceActivity extends Activity{
private BookService bookservice;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_activity);
//与service 绑定
Intent intent = new Intent(GetServiceActivity.this,BookService.class);
Book book = new Book ();
book.setBookname("陈世滔的书");
book.setAuthor("陈世滔");
intent.putExtra("book", book);
bindService(intent, conn, Context.BIND_AUTO_CREATE);

TextView textview = (TextView)findViewById(R.id.text);
textview.setText("绑定service服务");
}

private ServiceConnection conn = new ServiceConnection() {
/** 获取服务对象时的操作 */
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
bookservice = ((BookService.ServiceBinder) service).getService();

}

/** 无法获取到服务对象时的操作 */
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
bookservice = null;
}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
}


3.服务程序

package com.example.service;

import com.example.model.Book;

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

public class BookService extends Service {
boolean threadDisable;
private int count;
private Book book;

public void onCreate()
{
Log.i("oncreate", "bookservice already created");
super.onCreate();
/** 创建一个线程,每秒计数器加一,并在控制台进行Log输出 */
new Thread(new Runnable() {
public void run() {
while (!threadDisable) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {

}
count++;
Log.v("CountService", "Count is" + count+"bookname id"+book.getBookname());
}
}
}).start();
};
@Override
public IBinder onBind(Intent intent) {
book = intent.getParcelableExtra("book");
Log.i("onbind", "bookservice already onbind");
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("onstartCommand", "bookservice already onstartcommand");
book = intent.getParcelableExtra("book");
return super.onStartCommand(intent, flags, startId);
}

@Override
public boolean onUnbind(Intent intent) {
Log.i("onunbind", "bookservice already onunbind");

return super.onUnbind(intent);
}

@Override
public void onDestroy() {
this.threadDisable=true;
Log.i("ondestory", "bookservice already ondestory");
super.onDestroy();
}

//此方法是为了可以在Acitity中获得服务的实例
public class ServiceBinder extends Binder {
public BookService getService() {
return BookService.this;
}
}

public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}

}

4.book.java 通过Parcelable的方式传递数据

package com.example.model;

import android.os.Parcel;
import android.os.Parcelable;

public class Book implements Parcelable{
private String bookname;
private String author;
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(bookname);
dest.writeString(author);
}
public Book(){}
public Book(Parcel in)
{
this.bookname = in.readString();
this.author = in.readString();
}

public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
@Override
public Book createFromParcel(Parcel source) {
return new Book(source);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};

}

5.总结
5.1通过startService启动Service 时顺序为
onCreate()->onStartCommand()

5.2通过onbind启动service时启动顺序为
oncreate()->onBind()

5.3 stop关闭service时,关闭顺序为
直接执行ondestory()

5.4 unbind关闭时,关闭比顺序为
onbind()->ondestory()