1

嗨,我是 android 新手,正在探索服务部分。我无法使用绑定方法绑定服务。我不知道是绑定方法的问题还是连接的服务有问题。有人请帮助我。提前致谢

活动代码:

public class MainActivity extends AppCompatActivity {
MyService pavan ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Intent i = new Intent(this,MyService.class);
    this.startService(i);
    System.err.println("before binding**************************");
    this.bindService(i, con, Context.BIND_AUTO_CREATE);
    this.unbindService(con);this.stopService(i);
}
public ServiceConnection con = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        pavan = ((MyService.localbinder)service).getservice();
        System.err.println("here service gets binded");
        Toast.makeText(getBaseContext(),"Service connected",Toast.LENGTH_LONG);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(getBaseContext(),"oops this is moment of Service disconnected",Toast.LENGTH_LONG);
    }
};

}

服务代码:

public class MyService extends Service {
public MyService() {
}
public class localbinder extends Binder{
    public MyService getservice(){
        return MyService.this;
    }
}
IBinder ibinder = new localbinder();;


@Override
public IBinder onBind(Intent intent) {
            return ibinder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return Service.START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();

}

}

清单代码:

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.coolguy.pract">
    <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/>
    <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"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>
4

1 回答 1

0

最后我在我的代码中遇到了问题。Context.BIND_AUTO_CREATE 自动调用 startService()。所以当我调用 bind 方法时,因为服务已经在运行,它转到 onStartCommand。所以不要使用带有 Context.BIND_AUTO_CREATE 标志的 startservice。

于 2016-03-01T16:56:27.973 回答