1
嗨,我是新来的android和探索服务部分。我无法绑定服务使用绑定方法。我无法弄清楚它是绑定方法还是服务连接问题。有人请帮助我提前it.ThanksAndroid服务无法绑定
活动代码:
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>
你怎么知道你的代码不工作? – AlbAtNf
System.err.println(“这里的服务被绑定”);内部onserviceconnected不被调用。所以我认为onserviceconnected不被称为 –
我甚至尝试调用按钮单击绑定,因为绑定是异步的。但徒劳无益 –