2013-09-22 12 views
14

Chciałem wykonać usługę, która będzie sprawdzać moją wiadomość SMS co 20 sekund, jeśli są jakieś nieprzeczytane wiadomości SMS, a następnie wysłać ją na moją stronę internetową, a następnie oznaczyć jako przeczytaną dla opublikowania danych na stronie użyłem asynctask i to działało dobrze, gdy próbowałem ręcznie (poprzez przycisk typu click aplikację) ale w służbie bocznej nie mogę określićNie można wywołać metody runOnUiThread w wątku z wnętrza usługi

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

nie jest w stanie zidentyfikować i prosi mnie do zdefiniowania runOnUiThread Czy istnieje jakikolwiek sposób wywoływania mojego asynktaksu z miejsca, w którym dzwonię poniżej kodu:

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 Ta odpowiedź może być pomocna –

+0

Usługa nie zawiera wątku interfejsu użytkownika, ponieważ usługa nie ma interfejsu użytkownika. Myślę, że jest to (dobry) powód brakującej funkcji runOnUiThread. Musisz uruchomić swój kod w Mainthread Services. –

Odpowiedz

49

Service nie ma metody o nazwie runOnUiThread(). Zakładasz, że metoda z Activity jest również zdefiniowana dla Service, ale tak nie jest.

Rozwiązanie, po prostu zdefiniuj metodę, która dokładnie to robi. Oto uproszczony przykład, reszta kodu pozostanie niezmieniona.

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

} 

Aby uzyskać więcej informacji, see the docs for Handler. Służy do zrzucania pracy do określonego wątku. W takim przypadku Handler zostaje powiązany z wątkiem interfejsu użytkownika, ponieważ wątek interfejsu zawsze wywołuje Service.onCreate().

+0

unnable zdefiniować jak to pokazuje błąd * Nie można instancję typu Handler * kiedy piszę 'handler = new Handler();' w onCreate –

+0

Upewnij się, że 'android.os.Handler import;' – wsanville

+0

I zaimportowałem go, sprawdziłem. Nawet jeśli bym tego nie zrobił, sugeruje zaimportować –

Powiązane problemy