2016-07-29 76 views
0

嗨,項目中我正在使用服務進行使用SignalR的聊天通信。聊天通信工作正常,但是當應用程序被切換到後臺的服務得到了停止我需要完全運行的服務,直到我的應用程序被刪除當應用程序變爲背景時,服務已停止

這裏是我的服務代碼

public class SignalRService extends Service { 
private HubConnection mHubConnection; 
private HubProxy mHubProxy; 
private Handler mHandler; // to display Toast message 
private final IBinder mBinder = new LocalBinder(); // Binder given to clients 

public SignalRService() { 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 
    mHandler = new Handler(Looper.getMainLooper()); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    int result = super.onStartCommand(intent, flags, startId); 
    startSignalR(); 
    return result; 
} 

@Override 
public void onDestroy() { 
    Log.i("onDestroy","onDestroy"); 
    mHubConnection.stop(); 
    super.onDestroy(); 
} 

@Override 
public IBinder onBind(Intent intent) { 
    // Return the communication channel to the service. 
    startSignalR(); 
    return mBinder; 
} 

/** 
* Class used for the client Binder. Because we know this service always 
* runs in the same process as its clients, we don't need to deal with IPC. 
*/ 
public class LocalBinder extends Binder { 
    public SignalRService getService() { 
     // Return this instance of SignalRService so clients can call public methods 
     return SignalRService.this; 
    } 
} 

/** 
* method for clients (activities) 
*/ 
public void sendMessage(String message) { 
    String SERVER_METHOD_SEND = "Send"; 
    mHubProxy.invoke(SERVER_METHOD_SEND, message); 
} 

/** 
* method for clients (activities) 
*/ 
public void sendMessage_To(String receiverName, String message) { 
    String SERVER_METHOD_SEND_TO = "SendChatMessage"; 
    mHubProxy.invoke(SERVER_METHOD_SEND_TO, receiverName, message); 
} 

private void startSignalR() { 
    Platform.loadPlatformComponent(new AndroidPlatformComponent()); 
    Credentials credentials = new Credentials() { 
     @Override 
     public void prepareRequest(Request request) { 
      request.addHeader("User-Name", "BNK"); 
     } 
    }; 

    String serverUrl = "http://10.10.10.180/signalr/hubs"; 
    mHubConnection = new HubConnection(serverUrl); 
    mHubConnection.setCredentials(credentials); 
    String SERVER_HUB_CHAT = "ChatHub"; 
    mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT); 
    ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger()); 
    SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport); 

    try { 
     signalRFuture.get(); 
    } catch (InterruptedException | ExecutionException e) { 
     Log.e("SimpleSignalR", e.toString()); 
     return; 
    } 

    sendMessage("Hello from BNK!"); 

    String CLIENT_METHOD_BROADAST_MESSAGE = "broadcastMessage"; 
    mHubProxy.on(CLIENT_METHOD_BROADAST_MESSAGE, 
      new SubscriptionHandler1<CustomMessage>() { 
       @Override 
       public void run(final CustomMessage msg) { 
        final String finalMsg = msg.UserName + " says " + msg.Message; 
        // display Toast message 
        mHandler.post(new Runnable() { 
         @Override 
         public void run() { 
          Log.i("message","message: "+finalMsg); 
          Toast.makeText(getApplicationContext(), finalMsg, Toast.LENGTH_SHORT).show(); 
         } 
        }); 
       } 
      } 
      , CustomMessage.class); 
}} 

這裏是活動代碼

public class MainActivity extends AppCompatActivity { 

private final Context mContext = this; 
private SignalRService mService; 
private boolean mBound = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Intent intent = new Intent(); 
    intent.setClass(mContext, SignalRService.class); 
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
} 

@Override 
protected void onStop() { 
    // Unbind from the service 
    Log.i("onStop","onStop"); 
    if (mBound) { 
     unbindService(mConnection); 
     mBound = false; 
    } 
    super.onStop(); 
} 

public void sendMessage(View view) { 
    if (mBound) { 
     // Call a method from the SignalRService. 
     // However, if this call were something that might hang, then this request should 
     // occur in a separate thread to avoid slowing down the activity performance. 
     EditText editText = (EditText) findViewById(R.id.edit_message); 
     EditText editText_Receiver = (EditText) findViewById(R.id.edit_receiver); 
     if (editText != null && editText.getText().length() > 0) { 
      String receiver = editText_Receiver.getText().toString(); 
      String message = editText.getText().toString(); 
      mService.sendMessage_To(receiver, message); 
      mService.sendMessage(message); 
     } 
    } 
} 

/** 
* Defines callbacks for service binding, passed to bindService() 
*/ 
private final ServiceConnection mConnection = new ServiceConnection() { 

    @Override 
    public void onServiceConnected(ComponentName className, 
            IBinder service) { 
     // We've bound to SignalRService, cast the IBinder and get SignalRService instance 
     SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service; 
     mService = binder.getService(); 
     mBound = true; 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 

     Log.i("onServiceDisconnected","onServiceDisconnected"); 

     mBound = false; 
    } 
};} 

我的服務

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

PL代碼清單ese幫我解決這個問題

回答

1

如果你綁定了服務和任何組件,系統將自動銷燬服務,如果沒有其他客戶綁定它。

如果要獨立運行服務,則必須啓動服務而不是綁定。但你不能用,如果你有startService()

啓動有關詳細信息,你可以看到文檔here

+0

如果我刪除unbindService(mConnection);從onStop應用程序崩潰 – Jagan

+0

回答編輯,請檢查:) –

+0

你能爲我提供這種類型的服務的任何示例bcz我是新服務 – Jagan

0

你既可以啓動並綁定該服務的服務進行通信。

以這種方式,即使多個組件一次綁定到服務,那麼它們全部解除綁定,服務將會銷燬NOT。請參考

您的服務可以雙向工作:它可以啓動(無限期運行)並允許綁定。這僅僅是您是否實現了一對回調方法的問題:onStartCommand()允許組件啓動它,onBind()允許綁定。

// onBind method just return the IBinder, to allow clients to get service. 
@Override 
public IBinder onBind(Intent intent) { 
    return mBinder; 
} 

// onStartCommand just return START_STICKY to let system to 
// try to re-create the service if the servcie's process is killed. 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_STICKY; 
} 

// and make startSignalR public to allow client to call this method. 
public void startSignalR() { 
} 

在你的客戶,沒有必要保持一個布爾mBound

只需綁定服務onCreate,解除服務時onDestroy。當onStop時不要解除綁定。由於onStop可能會多次調用,例如對話框彈出將調用onStop,但是您的活動仍處於前臺,這會導致您的服務被破壞。

有關示例代碼,請參閱my answer for question: Pass Service From one Activity to Another