BindService总是不对
MyBindService.class
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class MyBindService extends Service {
@Override
public void onCreate() {
Log.i("info", "bind onCreate");
super.onCreate();
}
@Override
public void unbindService(ServiceConnection conn) {
Log.i("info", "bind unbindService");
super.unbindService(conn);
}
@Override
public void onDestroy() {
Log.i("info", "bind onDestroy");
super.onDestroy();
}
public class MyBinder extends Binder {
public MyBindService getService() {
return MyBindService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("info", "bind onBind");
return new MyBinder();
}
public void Play() {
Log.i("info", "播放");
}
public void Pause() {
Log.i("info", "暂停");
}
public void Shang() {
Log.i("info", "上首");
}
public void Next() {
Log.i("info", "下首");
}
}Activity
package com.example.myapplication;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
Intent intent;
MyBindService service;
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service=((MyBindService.MyBinder)binder).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doClick(View v) {
intent = new Intent(MainActivity.this, MyBindService.class);
switch (v.getId()) {
case R.id.bind:
bindService(intent,connection, Service.BIND_AUTO_CREATE);
break;
case R.id.unbind:
unbindService(connection);
break;
case R.id.play:
service.Play();
break;
case R.id.pause:
service.Pause();
break;
case R.id.shang:
service.Shang();
break;
case R.id.next:
service.Next();
break;
}
}
}Manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyBindService"></service> </application> </manifest>