如何在更改方向时处理服务

时间:2016-07-03 17:00:49

标签: java android multithreading service

我正在制作一个用于学习目的的音乐播放器应用程序,但我陷入了用户决定更改设备方向的位置,我的应用程序总是重新创建哪个是坏的,我已设法保存所有其他数据,使用onRestoreInstanceState恢复,但我无法想到使用musicplayer service的好方法,下面是我的代码的一部分,它是很多代码所以我将专注于问题

public class ManagerActivty extends AppCompatActivity{

 //music player service object
 private MusicService musicService;

 //boolean to keep track of musicservice state
 private boolean musicBound = Boolean.FALSE;

  //Music service connection object
    private ServiceConnection musicServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        if(!instanceSaved) {
            MusicService.MusicBinder binder = (MusicService.MusicBinder) iBinder;
            musicService = binder.getService();
            musicService.setOnSongChangeListener(ManagerActivty.this);
            musicService.setOnPlayerStateChangedListener(ManagerActivty.this);
            new loadSongAsync().execute();
            musicBound = Boolean.TRUE;
            System.out.println("Music Service Connected");

        }

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        musicBound = Boolean.FALSE;
    }
};



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

//method to bind music service with my activity
 private void bindMusicService()
{
    playMusicIntent = new Intent(this, MusicService.class);
    bindService(playMusicIntent, musicServiceConnection, Context.BIND_AUTO_CREATE);
    startService(playMusicIntent);
    System.out.println("Binder Called");

}



@Override
protected void onStart() {
    super.onStart();

    //launch binder    
    bindMusicService();
}


  @Override
protected void onDestroy() {
 //stop service connection
    if (playMusicIntent != null) {
        stopGuiUpdates();
        unbindService(musicServiceConnection);
        stopService(playMusicIntent);
        musicService = null;
    }
    super.onDestroy();
}

}




 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    System.out.println("Saved Instances");
    outState.putBoolean(Constant.IS_MEDIA_PLAYING_PLAYING, musicService.isPlaying());
    outState.putInt(Constant.MEDIA_PLAYER_POSITION, musicService.getMediaPlayer().getCurrentPosition());
    outState.putBoolean(Constant.IS_MUSIC_REPLAY, musicService.isReplay());

}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    System.out.println("Retrieving Instances");

      //if null try to re-bind service
    if(musicService == null) {
        bindMusicService();

    }


}

当我尝试在方向更改后访问musicservice对象时,此代码会给我一个nullpointerexception,任何处理此问题的人都请求帮助。

2 个答案:

答案 0 :(得分:1)

每次用户旋转手机时,都会调用onCreate()方法。我建议将此行添加到您的xml

机器人:configChanges = “keyboardHidden |取向”

另外,了解有关Parcelable界面的事情。

答案 1 :(得分:1)

您可以将配置更改声明为 App Manifest.xml 文件中的<activity>标记

  

机器人:configChanges =&#34;取向| keyboardHidden&#34;

这是您可以在 Manifest.xml

<activity>标记中设置的完整属性列表
<activity android:allowEmbedded=["true" | "false"]
          android:allowTaskReparenting=["true" | "false"]
          android:alwaysRetainTaskState=["true" | "false"]
          android:autoRemoveFromRecents=["true" | "false"]
          android:banner="drawable resource"
          android:clearTaskOnLaunch=["true" | "false"]
          android:configChanges=["mcc", "mnc", "locale",
                                 "touchscreen", "keyboard", "keyboardHidden",
                                 "navigation", "screenLayout", "fontScale",
                                 "uiMode", "orientation", "screenSize",
                                 "smallestScreenSize"]
          android:documentLaunchMode=["intoExisting" | "always" |
                                  "none" | "never"]
          android:enabled=["true" | "false"]
          android:excludeFromRecents=["true" | "false"]
          android:exported=["true" | "false"]
          android:finishOnTaskLaunch=["true" | "false"]
          android:hardwareAccelerated=["true" | "false"]
          android:icon="drawable resource"
          android:label="string resource"
          android:launchMode=["multiple" | "singleTop" |
                              "singleTask" | "singleInstance"]
          android:maxRecents="integer"
          android:multiprocess=["true" | "false"]
          android:name="string"
          android:noHistory=["true" | "false"]  
          android:parentActivityName="string" 
          android:permission="string"
          android:process="string"
          android:relinquishTaskIdentity=["true" | "false"]
          android:screenOrientation=["unspecified" | "behind" |
                                     "landscape" | "portrait" |
                                     "reverseLandscape" | "reversePortrait" |
                                     "sensorLandscape" | "sensorPortrait" |
                                     "userLandscape" | "userPortrait" |
                                     "sensor" | "fullSensor" | "nosensor" |
                                     "user" | "fullUser" | "locked"]
          android:stateNotNeeded=["true" | "false"]
          android:taskAffinity="string"
          android:theme="resource or theme"
          android:uiOptions=["none" | "splitActionBarWhenNarrow"]
          android:windowSoftInputMode=["stateUnspecified",
                                       "stateUnchanged", "stateHidden",
                                       "stateAlwaysHidden", "stateVisible",
                                       "stateAlwaysVisible", "adjustUnspecified",
                                       "adjustResize", "adjustPan"] >   
    . . .
</activity>