2013-09-22 8 views
14

Volevo creare un servizio che controllasse il mio SMS ogni 20 secondi se ci sono degli SMS non letti, quindi li mando sul mio sito web e li contrassegno come letti per la pubblicazione dei dati al sito ho usato AsyncTask e ha funzionato bene quando ho provato manualmente (facendo tasto tipo click app) ma in servizio a bordo non posso definiscoImpossibile chiamare runOnUiThread in una discussione dall'interno di un servizio

runOnUiThread(new Runnable() { 
      @Override 
      public void run() { new MyAsyncTask().execute(sender,time,message);} 
     }); 

non è in grado di identificare e mi chiede di definire runOnUiThread c'è qualsiasi modo per chiamare il mio asynctask dal luogo in cui sto chiamando sotto il codice

public class TestService extends Service { 

    String sender = null; 
    String time = null; 
    String message = null; 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(getApplicationContext(), "Service Created", 1).show(); 
     super.onCreate(); 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(getApplicationContext(), "Service Destroy", 1).show(); 
     super.onDestroy(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Toast.makeText(getApplicationContext(), "Service Running ", 1).show(); 
     new Thread(new Runnable() { 

      public void run() { 
       ContentValues values = new ContentValues(); 
       Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox"); 
       String[] columns = new String[] { "_id", "thread_id", 
         "address", "person", "date", "body", "type" }; 
       Cursor cursor1 = getContentResolver().query(mSmsinboxQueryUri, 
        null, "read=0", null, null); 
       DateFormat formatter = new SimpleDateFormat(
        "dd/MM/yyyy hh:mm:ss.SSS"); 
       Calendar calendar = Calendar.getInstance(); 
       if (cursor1.getCount() > 0) { 
        cursor1.moveToFirst(); 
        do { 
         // Retrieving sender number 
         sender = (cursor1.getString(cursor1 
          .getColumnIndex(columns[2])).toString()); 
         // Retriving time of reception 
         long ms = cursor1.getLong(cursor1 
          .getColumnIndex(columns[4])); 
         calendar.setTimeInMillis(ms); 
         time = formatter.format(calendar.getTime()).toString(); 
         // Retriving the message body 
         message = (cursor1.getString(cursor1 
          .getColumnIndex(columns[5])).toString()); 
         runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           new MyAsyncTask() 
            .execute(sender, time, message); 
          } 
         }); 
        } while (cursor1.moveToNext());// end of while 
       }// end of if 
        // set as read 
       values.put("read", true); 
       getContentResolver().update(Uri.parse("content://sms/inbox"), 
        values, null, null); 
      } 
     }).start(); 
     return super.onStartCommand(intent, flags, startId); 
    } 

    private class MyAsyncTask extends AsyncTask<String, Integer, Double> { 

     @Override 
     protected Double doInBackground(String... params) { 
      postData(params[0], params[1], params[2]); 
      return null; 
     } 

     protected void onPostExecute(Double result) { 
      // pb.setVisibility(View.GONE); 
      Toast.makeText(getApplicationContext(), "command sent", 
       Toast.LENGTH_LONG).show(); 
     } 

     protected void onProgressUpdate(Integer... progress) { 
      // pb.setProgress(progress[0]); 
     } 

     public void postData(String sender, String time, String message) { 
      // Create a new HttpClient and Post Header 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(
       "http://www.mysite.co.nf/reciever.php"); 
      try { 
       // Add your data 
       List<NameValuePair> nameValuePairs = 
               new ArrayList<NameValuePair>(); 
       nameValuePairs.add(new BasicNameValuePair("sender", sender)); 
       nameValuePairs.add(new BasicNameValuePair("time", time)); 
       nameValuePairs.add(new BasicNameValuePair("message", message)); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       // Execute HTTP Post Request 
       HttpResponse response = httpclient.execute(httppost); 
      } catch (ClientProtocolException e) {} catch (IOException e) {} 
     } 
    } 
} 
+0

http://stackoverflow.com/a/28873148/2670370 Questa risposta può essere utile –

+0

Un servizio non ha thread UI perché un servizio non ha un'interfaccia utente. Penso che questa sia la (buona) ragione dietro la funzione runOnUiThread mancante. Devi eseguire il tuo codice sul Mainthread dei servizi. –

risposta

49

Service non ha un metodo chiamato runOnUiThread(). Supponendo che il metodo da Activity sia definito anche per un Service, ma non lo è.

Soluzione, basta definire un metodo che faccia esattamente questo. Ecco un esempio semplificato, il resto del codice rimarrà invariato.

import android.os.Handler; 

public class TestService extends Service { 

    Handler handler; 

    @Override 
    public void onCreate() { 
     // Handler will get associated with the current thread, 
     // which is the main thread. 
     handler = new Handler(); 
     super.onCreate(); 
    } 

    private void runOnUiThread(Runnable runnable) { 
     handler.post(runnable); 
    } 

} 

Per ulteriori informazioni, see the docs for Handler. È usato per fare un po 'di lavoro su un thread specifico. In questo caso, lo Handler viene associato al thread dell'interfaccia utente, poiché il thread dell'interfaccia utente chiama sempre Service.onCreate().

+0

unnable per definire in questo modo dimostra errore * Non è possibile creare un'istanza del tipo Handler * quando scrivo 'handler = new Handler();' in onCreate –

+0

Assicurarsi di avere 'android.os.Handler importazione;' – wsanville

+0

I l'ho importato, controllato. Anche se non l'avessi fatto suggerirebbe di importare –

Problemi correlati