2017-07-21 37 views
0

我有一項服務,兩項活動和一個擴展應用程序。 所以我擔心的是,如果我在一個活動中實現應用程序,它會在我切換到下一個活動後丟失。這個想法是在我的應用程序類的幫助下,在這兩個活動中使用服務對象。那麼,我該如何實現它才能在我的兩個活動中擁有相同的應用程序類?如何使用應用程序類來啓動服務並將其用於我的活動?

public class AppController extends Application { 
boolean bound = false; 
private static AppController mInstance; 

private LocalService mBoundService; 

private ServiceConnection mConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     mBoundService = ((LocalService.LocalBinder) service).getService(); 
     System.out.println("Connected!!!!"); 
     bound = true; 
    } 

    public void onServiceDisconnected(ComponentName className) { 
     mBoundService = null; 
     bound = false; 
    } 
}; 


public static synchronized AppController getInstance() { 
    return mInstance; 
} 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
} 
public void startService(){ 
    //start your service 

} 
public void stopService(){ 
    //stop service 
} 
public LocalService getService(){ 
    return mBoundService; 
} 
} 
+0

嘗試使用片段,以便服務對象不會丟失 – karthik

+0

AppController.getInstance();如果我按下按鈕時使用空指針。 –

+0

在Activity中使用以下代碼LocalService服務= ((AppController)getApplication())。getService();會做你的工作。 –

回答

0

答案就是實現它在應用程序類這樣

public class AppController extends Application { 
boolean bound = false; 
private static AppController mInstance; 

private LocalService mBoundService; 

/** 
* The Background Service, which is started to communicate with multiple activities 
*/ 
private ServiceConnection mConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     mBoundService = ((LocalService.LocalBinder) service).getService(); 
     System.out.println("Connected!!!!"); 
     bound = true; 
    } 

    public void onServiceDisconnected(ComponentName className) { 
     mBoundService = null; 
     bound = false; 
    } 
}; 


public static synchronized AppController getInstance() { 
    return mInstance; 
} 


/** 
* With the start of app controller, the Service starts too 
*/ 
public void onCreate() { 
    startService(new Intent(this, LocalService.class)); 
    doBindService(); 
    super.onCreate(); 
} 
public void startService(){ 

} 
void doBindService() { 
    bindService(new Intent(this, 
      LocalService.class), mConnection, Context.BIND_AUTO_CREATE); 
} 

public void stopService(){ 
    //stop service 
} 
public LocalService getService(){ 
    return mBoundService; 
} 
public void test(){ 
    System.out.println("Test"); 
} 
} 

隨着廣播接收器,那麼你可以與活動通信。

相關問題