1

我对 Android 开发和 StackOverflow 都还很陌生,我希望我没有问一个以前被问过但我找不到任何东西的愚蠢问题。

我正在制作一个应用程序,该应用程序在连接到蓝牙设备时启动(最初未绑定)服务,并且只有在我告诉它断开连接或断开连接时才应该停止。服务启动后,主要活动绑定到它,并且在调用 onDestroy() 时将解除绑定。当调用 onStart 并且 mIsBound 为真时,它也会重新绑定。mIsBound 布尔值与 onRestoreInstanceState() 一起存储。

*mIsConnected 可能是一个比 mIsBound 更好的名字,但你明白了

当我正常重新打开应用程序时,从多任务菜单或通过服务图标 mIsBound 仍然设置为正确的值。屏幕方向不是问题,当打开辅助活动并通过后退按钮返回主要活动时,一切仍然顺利。但是,当我在辅助活动中使用向上按钮时,mIsBound 值会丢失,并且不会调用 onRestoreInstanceState()。

我需要这个来确定服务是否已经在运行,因为如果它不是并且我调用 bindService() 它将在不需要它的情况下启动,并且当它自行停止但仍被绑定时我会得到错误。

服务:

public class BluetoothService extends Service {

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

}

public class LocalBinder extends Binder {
    BluetoothService getService() {
        return BluetoothService.this;
    }
}


private void connectionLost() {
Log.e(TAG, "connection lost");
disconnect();
}


public synchronized void disconnect() {
    Log.d(TAG, "disconnect");
    stopSelf();
}


private void showNotification(String s) {

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.ic_launcher, s,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, LedAndIrControlActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, s, s, contentIntent);

    // Send the notification.
    startForeground(NOTIFICATION, notification);
}

主要活动:

public class MainActivity extends Activity {   

private static boolean mIsBound = false;
private BluetoothService Com;

@Override
public void onStart() {
    super.onStart();
    if(mIsBound){
        doBindService();
 }

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.i(TAG, "onSaveInstanceState");
    outState.putBoolean("mIsBound", mIsBound);
}

public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);          
    Log.i(TAG, "onRestoreInstanceState");
    mIsBound = savedInstanceState.getBoolean("mIsBound");
    if(mIsBound){
        doBindService();
    }
}

protected void onDestroy() {
    super.onDestroy();
    Log.i(TAG, "onDestroy");
    doUnbindService();
}

public boolean onOptionsItemSelected(MenuItem item) {
    Intent serverIntent = null;
    switch (item.getItemId()) {
    case android.R.id.home:
        return true;
    case R.id.item1:
         // Launch the DeviceListActivity to see devices and do scan
         serverIntent = new Intent(this, DeviceListActivity.class);
         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
         startService(new Intent(this, BluetoothService.class));
         doBindService();
         return true;
     case R.id.item2:
         // Disconnect device
        Com.disconnect();
        doUnbindService();
         return true;
     case R.id.item3:
          serverIntent = new Intent(this, SecondaryActivity.class);
          //serverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(serverIntent);
        return true;    
    default:
        return super.onOptionsItemSelected(item);
     }      
 } 

 void doBindService() {
     Log.d(TAG, "doBindService");
     // Establish a connection with the service.  We use an explicit
     // class name because we want a specific service implementation that
     // we know will be running in our own process (and thus won't be
     // supporting component replacement by other applications).
     bindService(new Intent(getBaseContext(), //Binding.this
             BluetoothService.class), mConnection, Context.BIND_AUTO_CREATE);
     mIsBound = true;
 }

 void doUnbindService() {
     if (mIsBound) {
         Log.d(TAG, "doUnbindService");
         // Detach our existing connection.
         unbindService(mConnection);
         mIsBound = false;
     }
     Com = null;
 }


 private ServiceConnection mConnection = new ServiceConnection() {

     public void onServiceConnected(ComponentName className, IBinder service) {
         // This is called when the connection with the service has been
         // established, giving us the service object we can use to
         // interact with the service.  Because we have bound to a explicit
         // service that we know is running in our own process, we can
         // cast its IBinder to a concrete class and directly access it.
         Com = ((BluetoothService.LocalBinder)service).getService();
         invalidateOptionsMenu();
         Log.i(TAG, "Service connected");

         // Tell the user about this for our demo.
         Toast.makeText(getBaseContext(), "local_service_connected",//Binding.this
                 Toast.LENGTH_SHORT).show();
     }

     public void onServiceDisconnected(ComponentName className) {
         // This is called when the connection with the service has been
         // unexpectedly disconnected -- that is, its process crashed.
         // Because it is running in our same process, we should never
         // see this happen.
         Com = null;
         Toast.makeText(getBaseContext(), "local service_disconected",//Binding.this
                 Toast.LENGTH_SHORT).show();
     }
 };

次要活动:

public class SecondaryActivity extends Activity {      


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent serverIntent = null;
    switch (item.getItemId()) {
    case android.R.id.home:
        // app icon in action bar clicked; go home
        serverIntent = new Intent(this, MainActivity.class);
        serverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(serverIntent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }   
}

我的问题是如何确保始终恢复 mIsBound 值?我发现使用 SharedPreferences 是一种选择,但这似乎不是正确的方法。

任何其他关于如何绑定到服务的建议,如果它已经在运行,也很感激!

谢谢!

更新:

我想到了另一种解决问题的方法,那就是简单地检查服务是否已经在运行,然后(重新)绑定(如果为真)。这里解释了这样做的方式: 如何检查服务是否在 Android 上运行?

我仍然不相信这是正确或最好的方法,但它现在可以。如果您对此发表评论,我们将不胜感激。

4

1 回答 1

1

我对您的帖子主题有同样的问题(当使用向上按钮时 onRestoreInstanceState 未被调用),尽管原因与您在正文中描述的原因不同。由于我还没有找到任何其他帖子来回答它,我将在这里发布我对这个特定问题的解决方案。

问:使用向上按钮时 onRestoreInstanceState 没有被调用

答:按下操作栏上的主页(向上导航)按钮确实与按下后退按钮的行为不同。前者不会调用onRestoreInstanceState()父 Activity 的 ,就像按下后退按钮一样。

如果您想完成与后退按钮相同的行为,您可以通过覆盖onNavigateUp()子活动中的方法并从中调用onBackPressed()来实现。

在子活动中:

@Override
public boolean onNavigateUp() {
    onBackPressed();
    return true;
}

我不确定返回值,true似乎工作正常并满足文档:“如果向上导航成功完成并且此活动完成,则为 true,否则为 false”

于 2013-08-28T15:55:51.597 回答