2016-07-29 7 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); 
}} 

であり、ここではアクティビティコードですサービス

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

P1のための

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; 
    } 
};} 

私のマニフェストコード

答えて

1

サービスを任意のコンポーネントにバインドすると、他のクライアントがバインドされていない場合、システムはサービスを自動的に破棄します。

サービスを単独で実行する場合は、バインドする代わりにサービスを開始する必要があります。しかし、あなたはより多くの詳細についてはstartService()

でそれを起動する場合は、サービスと通信することはできませんあなたがドキュメントhere

+0

unbindService(mConnection)を削除した場合。 onStopアプリからクラッシュする – Jagan

+0

回答を編集しました。確認してください:) –

+0

サービスのこのタイプのサンプルを私に提供してもらえますか? – Jagan

0

を見ることができますが、起動してサービスをバインドすることができBOTH。このようにして

、複数のコンポーネントを一度サービスにバインドしても、その後、それらのすべてがバインド解除、サービスが破壊されないます。 A service can essentially take two forms: Bound

サービスは両方の方法で動作します。サービスを開始する(無限に実行する)ことができ、バインディングも許可することができます。コンポーネントの起動を許可するonStartCommand()とバインディングを許可するonBind()の2つのコールバックメソッドを実装するかどうかの問題です。あなたの顧客に

// 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を参照してください。

関連する問題