2012-12-10 34 views
2

我希望在進入手機主菜單,與服務器連接以及如果收到消息顯示定製烤麪包之後,服務工作。我做了大部分,但我只能在烤麪包片上顯示文字。 我想用圖像製作自定義的烤麪包,我發現很多解決方案如何在活動中做到這一點,但它不適用於服務。安卓定製烤麪包服務

有人能告訴我該更改哪些代碼才能正常工作?

public class MyService extends Service { 
    private Toast toast; 
    private Timer timer; 
    private TimerTask timerTask; 
    private class MyTimerTask extends TimerTask { 
     @Override 
     public void run() { 
      showToast(); 
     } 
    } 

    private void showToast() { 

     LayoutInflater inflater = (LayoutInflater) 
      getSystemService(LAYOUT_INFLATER_SERVICE); 
     View layout = inflater.inflate(R.layout.toast, null); 
     ImageView image = (ImageView) 
      layout.findViewById(R.id.image); 
     image.setImageResource(R.drawable.truck); 
     TextView textView = (TextView) 
      layout.findViewById(R.id.text); 
     textView.setText("Some toast message"); 
     toast = new Toast(getApplicationContext()); 
     toast.setGravity(Gravity.BOTTOM, 0, 0); 
     toast.setDuration(Toast.LENGTH_LONG); 
     toast.setView(layout); 
     toast.show(); 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     timer = new Timer(); 
     toast = Toast.makeText(this, "", Toast.LENGTH_SHORT); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     clearTimerSchedule(); 
     initTask(); 
     timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000); 
     return super.onStartCommand(intent, flags, startId); 
    } 

    private void clearTimerSchedule() { 
     if(timerTask != null) { 
      timerTask.cancel(); 
      timer.purge(); 
     } 
    } 

    private void initTask() { 
     timerTask = new MyTimerTask(); 
    } 

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

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 
} 
+0

我想你不能自定義敬酒。無論如何,我會很高興被證明是錯誤的! :) – LittleSweetSeas

+0

請參閱http://developer.android.com/design/patterns/confirming-acknowledging.html以確認您在此處正確使用敬酒。 – adamp

+1

@adamp我只需要通知用戶,他不必確認他看到了,但他也可以確認,我只需要顯示信息 – akuzma

回答

0

作爲我們的願望,可以定製吐司。它已經在開發者網站上提及過了。檢查以下鏈接http://developer.android.com/guide/topics/ui/notifiers/toasts.html

+0

thx,你推我前進,但我仍然有很多問題,並決定不同的解決方案工作,我會把這個解決方案在這裏在10個小時內,我現在做的名譽太低 – akuzma

1

我以其他有點原始的方式解決了我的問題,但也許它會幫助與我有同樣問題的人。

我從吐司辭職,並創造了新的活動看起來像對話框

在清單:

<activity android:label="@string/app_name" 
      android:name="YourDialog" 
      android:theme="@android:style/Theme.Dialog" 
      android:taskAffinity=""/> 

和服務:

Intent dialog = new Intent(this, YourDialog.class); 
    dialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(dialog); 
+0

無法使用因爲YouDialog.class拋出一個錯誤。 它說「構造函數Intent(new Runnable(){},類)未定義。」 – akatran

+0

我的錯誤!我試圖通過一個新的runnable啓動Intent! – akatran