2017-07-21 6 views
0

私はサービスと2つのアクティビティと拡張アプリケーションを持っています。 私は、アクティビティでアプリケーションを実装すると、次のアクティビティに切り替えた後にアプリケーションが失われることを懸念しています。アイデアは、私のアプリケーションクラスの助けを借りて、これらの両方のアクティビティでサービスオブジェクトを使用することです。だから私はどのように私の両方の活動で同じアプリケーションクラスを持つためにそれを実装する必要がありますか?サービスを開始して自分の活動で使用するためにアプリケーションクラスを使用するにはどうすればよいですか?

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

アクティビティで次のコードを使用します。LocalService service = ((AppController)getApplication())。getService();あなたの仕事をします。 –

答えて

0

答えは、あなたが、その後の活動と通信できるBroadCastReceiverでこの

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

のようなアプリケーションクラスでそれを実装することです。

関連する問題