2013-07-17 6 views
1

У меня есть проблема с моим сервисом. У меня есть 3 кнопки, первая услуга вызова, чтобы получить номера в randon и показывать их в текстовом поле каждые 10 секунд, вторая услуга вызова кнопок, чтобы получать номера в rand каждый раз, когда я нажимаю эту кнопку, и последняя кнопка должна останавливаться службы, но я не могу, когда я нажимаю на нее, и когда я закрываю приложение и снова открываю сервис автоматически запускаюсь, я не понимаю !!Я не знаю, как остановить мое обслуживание

Существует мой класс

public class MyService extends Service{ 
public static final String NEW_DATA = "com.example.t8ej1.MyService.NEW_DATA"; 
private static final String stringUrl = 
"http://www.imaginaformacion.com/recursos/rand.php"; 
private static final int updateInterval = 1000; 
private Timer updateTimer; 
private TimerTask doRefresh; 
private String data; 
public int service_id; 
private IBinder binder = new MyBinder(); 

public class MyBinder extends Binder { 
MyService getService() { 
return MyService.this; 
}} 

private void updateData() { 
    // Nos conectamos al servicio web y obtenemos los datos 

    try{ 

     URL url = new URL(stringUrl); 
     HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection(); 
     int responseCode = httpURLConnection.getResponseCode(); 
     if(responseCode == HttpURLConnection.HTTP_OK){ 
      InputStream in = httpURLConnection.getInputStream(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
      data= reader.readLine(); 
      in.close(); 
      announceData(); 


     } 

    } 

    catch(MalformedURLException e){ 
     Log.e("Service", e.getMessage()); 
    }catch(IOException e){ 
     Log.e("Service", e.getMessage()); 
    } 
} 

private void announceData() { 
    // Lanzamos el broadcast con el intent y los datos 

    Intent intent = new Intent(NEW_DATA); 
    intent.putExtra("data", data); 
    sendBroadcast(intent); 
} 

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



@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // TODO Auto-generated method stub 
    // Creamos el Timer y el TimerTask 

    service_id=startId; 
    updateTimer = new Timer(); 
    doRefresh = new TimerTask() { 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub    
      updateData(); 
     } 
    }; 
    // Lo programamos para que se lance cada updateInterval milisegundos 
    updateTimer.scheduleAtFixedRate(doRefresh, 0, updateInterval); 
    // Queremos que el servicio esté siempre encendido 


    return Service.START_STICKY; 
} 



@Override 
public void onDestroy() { 
    // TODO Auto-generated method stub 
    Log.e("mm", "4444"); 
    super.onDestroy(); 
} 


public String getData() { 
    return data; 
    }} 

сервис Существует мой класс активности

public class Service extends Activity { 
private MyServiceReceiver myReceiver; 
private MyService myService; 
TextView txtManual; 
TextView txtAuto; 

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

    bindService(new Intent(Service.this, MyService.class), 
      myConnection, 
      Context.BIND_AUTO_CREATE); 

    IntentFilter filter; 
    filter = new IntentFilter(MyService.NEW_DATA); 
    myReceiver = new MyServiceReceiver(); 
    registerReceiver(myReceiver, filter); 


txtAuto = (TextView) findViewById(R.id.txtAuto); 
txtManual = (TextView) findViewById(R.id.txtManual); 

Button cmdStart = (Button) findViewById(R.id.cmdStart); 
Button cmdRefresh = (Button) findViewById(R.id.cmdRefresh); 
Button cmdStop = (Button) findViewById(R.id.cmdStop); 

cmdStop.setOnClickListener(new OnClickListener() { 

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


     unbindService(myConnection); 

     stopService(new Intent(Service.this, MyService.class));   


    } 
}); 

cmdRefresh.setOnClickListener(new OnClickListener() { 
    @Override 

    public void onClick(View v) { 
    txtManual.setText(myService.getData()); 
    } 
    }); 


cmdStart.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

     startService(new Intent(Service.this, MyService.class)); 
    } 
}); 


} 

    private ServiceConnection myConnection = new ServiceConnection() { 

     @Override 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      // TODO Auto-generated method stub 
      myService = ((MyService.MyBinder) service).getService();  
     } 

     @Override 
     public void onServiceDisconnected(ComponentName name) { 
      // TODO Auto-generated method stub 
      myService=null; 
     } 


     }; 


public class MyServiceReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
    txtAuto.setText(intent.getStringExtra("data")); 



    } 

} 
@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; 
} 
@Override 



protected void onPause() { 
    // TODO Auto-generated method stub 
    //unregisterReceiver(myReceiver); 
    super.onPause(); 
} 

@Override 
protected void onDestroy() { 
    // TODO Auto-generated method stub 

    super.onDestroy(); 
} 
@Override 
protected void onStop() { 
    // TODO Auto-generated method stub 
    unregisterReceiver(myReceiver); 

    super.onStop(); 
} 
@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 

    super.onResume(); 
}} 
+0

http://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent, android.content .ServiceConnection, int). check bind and unbind http://developer.android.com/reference/android/content/Context.html#unbindService(android.content.ServiceConnection) – Raghunandan

ответ

0

отвязать обслуживание с использованиемunbindService() в вашем onStop() из MyService класса (YourService),

и затем вызватьstopService в Service классе (вашActivity)

+0

отключите службу, используя unbindService() в вашем onStop() класса MyService (ваша служба)? Вы говорите мне, что я должен создать методы onStop? –

+0

нет вам нужно переопределить метод onStop(), например onCreate()! что-то вроде: \t @Override \t защищен недействительным OnStop() { \t \t // TODO Auto-генерироваться метод заглушки \t \t super.onStop(); // отключите услугу здесь \t} –

+0

Но Myservice.class только имеет onDestroy метод для переопределения !! –