2011-10-15 1 views
0

우선이 검색을 시도했지만 ans는 실패했습니다. 내 질문에 이미 답변이 있다면 누군가 나를 가리켜 주시겠습니까? 이 문제를 보면서 나를 도와 주시거나 심지어 이것을 감추고 올바른 방향으로 나를 가리켜 주셔서 대단히 감사합니다. 나는 정말로 그것을 바르게 평가한다!AlertDialog에서 서비스 시작 및 바운드 활동이 외부에 있음

내 딜레마 : 나는 활동이 있으며 그 활동에는 목록보기가 있습니다. 목록보기에는 AlertDialog를 호출해야하는 항목이 여러 개 있습니다. AlertDialog는 "이봐, 일부 데이터를 업데이트해야 해."라는 서비스를 호출한다. 서비스는 청취하고 업데이트를 성공적으로 수행합니다.

문제는 내 활동이 서비스를 인정하지 않는다는 것입니다. 제가 궁금한 점은 서비스 운영 방식을 완전히 이해하지 못하고 동일한 서비스를 여러 번 실행/실행시킬 수 있다는 것입니다.

참고로, 예는 The Android Dev Reference for Service의 아이디어와 관련이 있습니다.

예 :

public class MyActivity extends Activity implements IMainActivity 
    { 
     ListView _list; 

     private RefreshConnector _serviceConnector; 

     private boolean _isBound; 

     public MyActivity() {} 

     public fillList() 
      { 
        //this won't trigger within the service 
      } 

      private void 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). 
        getApplicationContext().bindService(new Intent(this, UpdateScheduleService.class), _serviceConnector, BIND_AUTO_CREATE); 
        _isBound= true; 
      } 

      private void doUnbindService() 
      { 
        if (_isScheduleBound) 
        { 
          // Detach our existing connection. 
          getApplicationContext().unbindService(_serviceConnector); 
          _isBound= false; 
        } 
      } 

      @Override 
      protected void onDestroy() 
      { 
        super.onDestroy(); 
        doUnbindService(); 
      } 

      @Override 
      public void onCreate(Bundle savedInstanceState) 
      { 
        super.onCreate(savedInstanceState); 

        _isBound= false; 

        _list = (ListView) findViewById(R.id.TheList); 
        _list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        { 
          public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) 
          { 
            if (view != null) 
            { 
              CheckBox selectedFlag = (CheckBox) view.findViewById(R.id.selectedItem); 
              selectedFlag.setOnClickListener(new View.OnClickListener() 
              { 
                public void onClick(View view) 
                { 
                  doBindService(); 
                  Bundle extras = new Bundle(); 
                  extras.putBoolean(BundleLocations.BUNDLE_ENABLED, ((CheckBox) view).isChecked()); 
                  extras.putLong(BundleLocations.BUNDLE_SCHEDULE_ID, 123); //123 is an example of an id being passed 
                  extras.putString(BundleLocations.ACTION, BundleLocations.ACTION_SELECTED); 
                  Intent updateSelection = new Intent("ChangeItems"); 
                  updateSelection.putExtras(extras); 
                  view.getContext().startService(updateSelection); 
                } 
              }); 

              TextView description = (TextView) view.findViewById(R.id.description); 
              description.setText(s.getDescription()); 
              description.setOnClickListener(new View.OnClickListener() 
              { 
                public void onClick(View view) 
                { 
                  doBindService(); 
                  ChangeDescriptionDialog dia = new ChangeDescriptionDialog(view.getContext()); 
                  dia.setTitle(view.getContext().getResources().getString(R.string.DESCRIPTION_TITLE)); 
                  dia.setAction(BundleLocations.ACTION_DESCRIPTION); 
                  dia.setDescription("something new"); //simplified for example... 
                  dia.create(); 
                  dia.show(); 
                } 
              }); 
            } 
          } 
        }; 
      } 

RefreshConnector :

public class RefreshConnector implements ServiceConnection 
{ 
    private UpdateService service; 

    public IMainActivity getActivity() 
    { 
     return activity; 
    } 

    public void setActivity(IMainActivity value) 
    { 
     this.activity = value; 
    } 

    public UpdateScheduleService getService() 
    { 
     return service; 
    } 

    private IMainActivity activity; 

    public void onServiceConnected(ComponentName componentName, IBinder iBinder) 
    { 
     service = ((UpdateService.UpdateBinder)iBinder).getService(); 

     if(activity != null) 
      activity.fillList(); 
    } 

    public void onServiceDisconnected(ComponentName componentName) 
    { 
     service = null; 
    } 
} 

UpdateService

public class UpdateService extends Service 
{ 
    final public IBinder binder = new UpdateBinder(); 

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

    public class UpdateBinderextends Binder 
    { 
     public UpdateService getService() 
     { 
      return UpdateService .this; 
     } 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
     if (intent == null) 
     { 
      stopSelf(); 
      return START_STICKY; 
     } 

     if(action.equals(BundleLocations.ACTION_SELECTED)) 
     { 
      long id = intent.getExtras().getLong(BundleLocations.BUNDLE_ID); 
      boolean enabled = intent.getExtras().getBoolean(BundleLocations.BUNDLE_ENABLED); 

      if(id < 0) 
      { 
       return START_STICKY; 
      } 

      String item = intent.getExtras().getString(BundleLocations.BUNDLE_ITEM); 

      if (item == null || action.equals("")) return START_STICKY; 

      //do some work with saving the description, which it does 

      return START_STICKY; 
     } 

     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() 
    { 
     super.onDestroy(); 
    } 
} 

DescriptionDialog 절단 (생성자), 또한, 이는에 AlertDialog.Builder 클래스에서 확장된다. 기본적으로 _context를 저장하는 모든 대화 상자에서 공통적 인 클래스도 있습니다. 그래서 여기서는 컨텍스트가 슈퍼에 저장됩니다. _context가 보호되어 있습니다 ...

public ChangeDescriptionDialog(Context context) 
    { 
     super(context); 

     DialogInterface.OnClickListener onClickListenerPositive = new DialogInterface.OnClickListener() 
     { 
      public void onClick(DialogInterface dialog, int id) 
      { 
       //dispatch change 
       Intent ChangeItems = new Intent("ChangeItems"); 
       Bundle extras = new Bundle(); 
        extras.putParcelable(BundleLocations.BUNDLE_ITEM, _description); 
       extras.putString(BundleLocations.ACTION, _action); 
       ChangeItems.putExtras(extras); 

       // 
       // my question is partly here 
       // I start this service... 
       // 
       // How would my activity see it... right now it doesn't seem that way even though I do the binding before this call 
       // 
       _context.startService(ChangeItems); 
     } 
    }; 

    this.setPositiveButton(context.getResources().getString(R.string.DIALOG_POS), onClickListenerPositive); 
} 

다시 한 번 팝업이 발생하기 전에 바인딩이 발생합니다. 둘째, 바인딩에서 서비스를 시작합니다. 내가 뭘 잘못하고 있니?

는 그 결합 서비스를 필요로하지 않는 수행 할 작업을 할 수있는 더 쉬운 방법이 있습니다, 다시 켈리

+0

서비스가 데이터를 업데이트 한 후에는 무엇을하고 싶습니까? – Noel

+0

안녕하세요 노엘, 활동 목록을 새로 고침하고 싶습니다 – KellyTheDev

답변

0

여러분 모두 감사합니다.

먼저 서비스 대신 IntentService를 확장해야합니다. 그러면 서비스가 UI 스레드에서 실행되지 않습니다. 현재와 ​​같은 방식으로 인 텐트를 통해 서비스를 시작할 수 있습니다.

둘째, 서비스 구현시 BoundService를 사용하는 것보다 완료되었음을 알리기 위해 브로드 캐스트 메시지를 보내는 것이 훨씬 쉽습니다. 당신은 같은 것을 할 것이다 당신의 서비스에 그래서 :

Intent intent = new Intent(); // specify the intent filter appropriately here 
sendBroadcast(intent); 

다음을, 당신의 활동에 이러한 변경을 통보 할 것 BroadcastReciever을 등록 할 것입니다. 자세한 내용은 BroadcastReceiver doc을 참조하십시오.

+0

노엘을 공유해 주셔서 감사합니다! 나는 그것을 한방에주고보고 할 것이다. – KellyTheDev