2012-12-10 35 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