2016-03-01 127 views
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> 
+0

你怎麼知道你的代碼不工作? – AlbAtNf

+0

System.err.println(「這裏的服務被綁定」);內部onserviceconnected不被調用。所以我認爲onserviceconnected不被稱爲 –

+0

我甚至嘗試調用按鈕單擊綁定,因爲綁定是異步的。但徒勞無益 –

回答

0

最後我得到了我的時候調用bind方法,因爲服務已在運行自動調用startService(),所以在這裏我code.Context.BIND_AUTO_CREATE問題不言而喻onStartCommand.So只是不要使用帶有Context.BIND_AUTO_CREATE標誌的startservice。