2013-05-05 4 views
7

내 앱에서 수행하려는 작업 : 1. 사용자가 앱을 열면 이미 실행중인 카운트 다운 타이머를 볼 수 있습니다. 따라서이 경우 항상 매초마다 업데이트 될 카운트 다운 번호를 텍스트보기에 표시하려고합니다. 2. 사용자가이를 중지 할 수 있습니다. 3. 사용자는 응용 프로그램을 종료 할 수 있지만 응용 프로그램 UI로 돌아올 때 카운트 다운이 계속 진행되어 업데이트 된 시간을 표시해야합니다.백그라운드에서 서비스를 사용하여 카운트 다운 타이머 구현

위의 내용을 바탕으로 백그라운드에서 작동하는 Service를 구현해야한다는 것을 알고 있습니다. 내가 this 링크를 읽었지만 내 문제는 구현입니다. 나는 그 방법을 구현하는 방법에 대해 매우 분실했다. 즉, 사용자가 응용 프로그램으로 돌아 오면 UI에 시간을 표시하는 방법을 생각할 수도 없습니다. this link도 보았습니다 만 CountDownTimer를 구현하면 실행중인 서비스가되는지 확실하지 않습니다. 그럼 어떻게 진행하고 구현해야합니까? 특정 자습서/코드에 대한 링크가 제공됩니다. 감사.

업데이트 : 지금까지 다음 작업을 수행 할 수 있었다 : MainActivity.java를

public class MainActivity extends Activity { 

Button btnStart,btnStop; 
Intent serviceIntent; 
TextView tv; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    btnStart = (Button) findViewById(R.id.btnStart); 
    btnStop = (Button) findViewById(R.id.btnStop); 
    tv = (TextView) findViewById(R.id.timeView); 

    //final MyCounter timer = new MyCounter(100000,1000); 
    //tv.setText("100"); 
    //timer.start(); 
    serviceIntent = new Intent(MainActivity.this,MyService.class); 

    btnStart.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      startService(serviceIntent); 
     } 
    }); 

    btnStop.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      stopService(serviceIntent); 
     } 
    }); 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

MyService.java :

public class MyService extends Service { 

MyCounter timer; 
@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    timer = new MyCounter(100000,1000); 
    super.onCreate(); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // TODO Auto-generated method stub 
    timer.start(); 
    return super.onStartCommand(intent, flags, startId); 
} 
private class MyCounter extends CountDownTimer{ 

    public MyCounter(long millisInFuture, long countDownInterval) { 
     super(millisInFuture, countDownInterval); 
    } 

    @Override 
    public void onFinish() { 
     Toast.makeText(getApplicationContext(), "death", Toast.LENGTH_LONG).show(); 
     stopSelf(); 
    } 

    @Override 
    public void onTick(long millisUntilFinished) { 

     Toast.makeText(getApplicationContext(), (millisUntilFinished/1000)+"", Toast.LENGTH_SHORT).show(); 
    } 
} 

@Override 
public void onDestroy() { 
    // TODO Auto-generated method stub 
    timer.cancel(); 
    //stopSelf(); 
    super.onDestroy(); 

} 

@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

    } 

문제는 다음과 같습니다 1. 난 몰라 MainActivity UI에서 카운트 다운을 표시하는 방법을 알고 있어야합니다. 2. 정지 버튼을 누르면 카운팅이 멈추지 않습니다.

+0

당신이 통신으로 방송을 사용할 수 있습니다 생각이 당신을 도울 것입니다. –

+0

@GhalebKhaled 구현에 대해 설명해 주시겠습니까? vogella http://www.vogella.com/articles/AndroidServices/article.html에서 튜토리얼을 보았으며 방송 수신기가 어떻게 호출되는지 이해하는 데 도움이되지 못했습니다. – Arefin

+0

확인 http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html 및 http://www.edureka.in/blog/android-tutorials-broadcast-receivers/ 희망이 도움이 될 것입니다 –

답변

1

카운트 다운 서비스를 바인드하기 위해 bindService (Intent 서비스, ServiceConnection conn, int 플래그)를 사용하고, 서비스에서 개수가 포함 된 바인더를 반환하고 액티비티에서 인스턴스화 된 ServiceConnection 객체가 바인더를 처리 할 수 ​​있습니다. AIDL도이 작업을 수행 할 수 있습니다. 먼저 서비스를 묶는 방법을 살펴보고 소원이 도움이 될 수 있도록 제안하십시오.

데모

public class BindService extends Service{ 
private int count; 
private boolean quit; 
private MyBinder binder = new MyBinder(); 
// My Binder 
public class MyBinder extends Binder 
{ 
    public int getCount() 
    { 
     // get the counting status:count 
     return count; 
    } 
} 

@Override 
public IBinder onBind(Intent intent) 
{ 
    System.out.println("Service is Binded"); 
    // return the binder instance 
    return binder; 
} 

@Override 
public void onCreate() 
{ 
    super.onCreate(); 
    System.out.println("Service is Created"); 
    // counting work 
    new Thread() 
    { 
     @Override 
     public void run() 
     { 
      while (!quit) 
      { 
       try 
       { 
        Thread.sleep(1000); 
       } 
       catch (InterruptedException e) 
       { 
       } 
       count++; 
      } 
     } 
    }.start();  
} 
// invoke when the service unbind 
@Override 
public boolean onUnbind(Intent intent) 
{ 
    System.out.println("Service is Unbinded"); 
    return true; 
} 

@Override 
public void onDestroy() 
{ 
    super.onDestroy(); 
    this.quit = true; 
    System.out.println("Service is Destroyed"); 
} 

@Override 
public void onRebind(Intent intent) 
{ 
    super.onRebind(intent); 
    this.quit = true; 
    System.out.println("Service is ReBinded"); 
} 

}

후 활동

public class MainActivity extends Activity{ 
Button bind , unbind , getServiceStatus; 
BindService.MyBinder binder; 
// define a ServiceConnection object 
private ServiceConnection conn = new ServiceConnection() 
{ 
    // then the Activity connected with the Service, this will be called 
    @Override 
    public void onServiceConnected(ComponentName name 
     , IBinder service) 
    { 
     System.out.println("--Service Connected--"); 
     // achieve MyBinder instance 
     binder = (BindService.MyBinder) service; 
    } 
    // then the connection break off 
    @Override 
    public void onServiceDisconnected(ComponentName name) 
    { 
     System.out.println("--Service Disconnected--");   
    } 
}; 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    bind = (Button) findViewById(R.id.bind); 
    unbind = (Button) findViewById(R.id.unbind); 
    getServiceStatus = (Button) findViewById(R.id.getServiceStatus); 

    final Intent intent = new Intent(); 

    intent.setAction("org.crazyit.service.BIND_SERVICE");  
    bind.setOnClickListener(new OnClickListener() 
    { 
     @Override 
     public void onClick(View source) 
     { 
      //bind Serivce 
      bindService(intent , conn , Service.BIND_AUTO_CREATE); 
     } 
    }); 
    unbind.setOnClickListener(new OnClickListener() 
    { 
     @Override 
     public void onClick(View source) 
     { 
      //unbind Serivce 
      unbindService(conn); 
     } 
    }); 
    getServiceStatus.setOnClickListener(new OnClickListener() 
    { 
     @Override 
     public void onClick(View source) 
     { 
      // Toast to show the conut value 
      Toast.makeText(MainActivity.this 
       , "Serivce's count value is:" + binder.getCount() 
       , 4000) 
       .show(); 
     } 
    }); 
}} 
+0

bindService를 사용하여 시도했습니다. 내가 안드로이드와 물건에 새로운입니다 구현에 관해서는 항상 명확하지는 않습니다. – Arefin

+0

OK, 여기에 내 데모가 있습니다, 나는 당신에게 보여줄 나의 대답을 편집 할 것입니다. – 3h3

+0

서비스 상태 버튼을 클릭하면 앱이 다운됩니다 : ( – Arefin