2017-07-04 65 views
-2

我尝试创建我的第一个服务,当然没有成功。但这个应用程序成功编译,并没有给AndroidMonitor的任何错误。 总之,按钮没有反应按下。 我加入到Android清单需要行:吐司不在服务

<service android:name=".MyService"></service> 

ClientActivity

package com.example.servicetest; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 

public class ClientActivity extends Activity { 
    private Button btnStartService; 
    private Button btnStopService; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     btnStartService = (Button) findViewById(R.id.btnStartService); 
     btnStopService = (Button) findViewById(R.id.btnStopService); 
     initButtonsOnClick(); 
    } 

    private void initButtonsOnClick() { 
     OnClickListener listener = new OnClickListener() { 
      public void onClick(View v) { 
       switch (v.getId()) { 
        case R.id.btnStartService: 
         startMyService(); 
         break; 
        case R.id.btnStopService: 
         stopMyService(); 
         break; 
        default: 
         break; 
       } 
      } 
     }; 
     btnStartService.setOnClickListener(listener); 
     btnStopService.setOnClickListener(listener); 
    } 

    private void startMyService() { 
     Intent serviceIntent = new Intent(this, MyService.class); 
     startService(serviceIntent); 
    } 

    private void stopMyService() { 
     Intent serviceIntent = new Intent(this, MyService.class); 
     stopService(serviceIntent); 
    } 
} 

为MyService

package com.example.servicetest; 

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.util.Log; 
import java.util.Timer; 
import java.util.TimerTask; 
import android.widget.Toast; 

public class MyService extends Service { 
    private Toast toast; 
    private Timer timer; 
    private TimerTask timerTask; 
    private class MyTimerTask extends TimerTask { 
     @Override 
     public void run() { 
      Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show(); 
     } 
    } 


    private void writeToLogs(String message) { 
     Log.d("HelloServices", message); 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     writeToLogs("Called onCreate() method."); 
     timer = new Timer(); 
     Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     writeToLogs("Called onStartCommand() methond"); 
     clearTimerSchedule(); 
     initTask(); 
     timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000); 
     Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show(); 
     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() { 
     writeToLogs("Called onDestroy() method"); 
     clearTimerSchedule(); 
     Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show(); 
     super.onDestroy(); 
    } 

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

做'敬酒= Toast.makeText(getApplicationContext() “”,Toast.LENGTH_SHORT);' –

+0

仍然没有工作 – philips

回答

1

Toast总是与Application的主线程一起工作。所以你必须确定你在主线程中使用线程。

而如果你想使用吐司服务,那么你必须使用处理程序。

请线程检查出下面的例子对处理程序:

private Context mContext; 

@Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     mContext=getApplicationContext();//Get the context here 
    } 

    //Use this method to show toast 
    void showToast(){ 
     if(mContext != null){ 
     Handler handler = new Handler(Looper.getMainLooper()); 
     handler.post(new Runnable() { 
      @Override 
      public void run() 
      { 
        Toast.makeText(mContext, "Display your message here", Toast.LENGTH_SHORT)show(); 
      } 
     }); 

    } 
} 
0
public class MyService extends Service { 

    private Timer timer; 
    private TimerTask timerTask; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     startTimer(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     super.onStartCommand(intent, flags, startId); 
//  startTimer(); 
//  sendNotification(); 
     return START_STICKY; 
    } 


    public void startTimer() { 
     //set a new Timer 
     timer = new Timer(); 

     //initialize the TimerTask's job 
     initializeTimerTask(); 

     //schedule the timer, to wake up every 10 second 
     timer.schedule(timerTask, 5000, 5000); // 
    } 

    /** 
    * it sets the timer to print the counter every x seconds 
    */ 
    public void initializeTimerTask() { 
     timerTask = new TimerTask() { 
      public void run() { 
//    Log.e("in timer", "in timer ++++ " + (counter++)); 

       Handler handler = new Handler(Looper.getMainLooper()); 
       handler.post(new Runnable() { 

        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           ""+ (counter++), 
           Toast.LENGTH_SHORT).show(); 
        } 
       }); 
//    Toast.makeText(SensorService.this, ""+ (counter++), Toast.LENGTH_SHORT).show(); 
      } 
     }; 
    } 

    /** 
    * not needed 
    */ 
    public void stoptimertask() { 
     if (timer != null) { 
      timer.cancel(); 
      timer = null; 
     } 
    } 


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

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

用这个按钮点击

public class ClientActivity extends Activity { 

    private Button btnStartService; 
    private Button btnStopService; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     btnStartService = (Button) findViewById(R.id.btnStartService); 
     btnStopService = (Button) findViewById(R.id.btnStopService); 

     btnStartService.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent serviceIntent = new Intent(this, MyService.class); 
       startService(serviceIntent); 
      } 
     }); 

     btnStopService.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent serviceIntent = new Intent(this, MyService.class); 
       stopService(serviceIntent); 
      } 
     }); 
    } 

} 
+0

但现在还不是服务? – philips

+0

检查现在的代码。 –

2

A服务是可以在后台执行长时间运行的操作的应用组件,并且它不提供一个用户界面。 - 来自Android官方文档。

现在,因为服务没有用户界面,所以在使用服务时不能显示敬酒。

+1

它不是真的 - 你可以在'Services'中使用'Toasts',但它们是来自UI线程的'show()'n - 例如尝试从'onStartCommand'显示它们 – pskink

0
Handler handler = new Handler(Looper.getMainLooper()); 
handler.post(new Runnable() { 

    @Override 
    public void run() { 
     Toast.makeText(getApplicationContext(), 
         "helllo", 
         Toast.LENGTH_SHORT).show();    
    } 
}); 
0

添加在您的服务下面的代码

if (getActivity()!=null){ 
         getActivity().runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           Toast.makeText(getActivity(), "Your Text", Toast.LENGTH_SHORT).show(); 

          } 
         }); 
        }