package com.example.servicebrodemo;
import com.example.servicebrodemo.service.MyService;
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.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
private MyConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection = new MyConnection(); // 忘记参数初始化。
}
public void start(View v) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stop(View v) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
//绑定服务,其实是 activty 链接到service。
public void bind(View v) {
Intent intent = new Intent(this, MyService.class);
bindService(intent, connection, BIND_AUTO_CREATE);
}
//解绑服务,conn 是一个链接。
public void unbind(View v) {
unbindService(connection);
}
class MyConnection implements ServiceConnection {
//服务建立连接,调用此方法。
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
//服务连接接触,嗲用次方法。
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
import com.example.servicebrodemo.service.MyService;
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.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
private MyConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection = new MyConnection(); // 忘记参数初始化。
}
public void start(View v) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stop(View v) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
//绑定服务,其实是 activty 链接到service。
public void bind(View v) {
Intent intent = new Intent(this, MyService.class);
bindService(intent, connection, BIND_AUTO_CREATE);
}
//解绑服务,conn 是一个链接。
public void unbind(View v) {
unbindService(connection);
}
class MyConnection implements ServiceConnection {
//服务建立连接,调用此方法。
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
//服务连接接触,嗲用次方法。
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
出现非法异常 ; 原因在意,传入的参数未进行初始化,(MyConnection 类没有进行初始化。)