Java 吐司不在服务中工作

Java 吐司不在服务中工作,java,android,Java,Android,我试图创建我的第一个服务,当然没有成功。但此应用程序已成功编译,并且在AndroidMonitor中未给出任何错误。 简而言之,按下按钮时没有反应。 我在Android清单的必填行中添加了: <service android:name=".MyService"></service> MyService package com.example.servicetest; import android.app.Service; import android.content.

我试图创建我的第一个服务,当然没有成功。但此应用程序已成功编译,并且在AndroidMonitor中未给出任何错误。 简而言之,按下按钮时没有反应。 我在Android清单的必填行中添加了:

<service android:name=".MyService"></service>
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;
    }
}
使用此按钮单击

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

}

Toast始终与应用程序的主线程配合使用。所以您必须确保在主线程中使用线程

而且,如果您想在服务中使用Toast,那么您必须使用Handler

请查看以下线程中处理程序的示例:

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

    }
}

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


现在,由于服务没有ui,所以在使用服务时不能显示toast。

在服务中添加以下代码

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

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

                            }
                        });
                    }

Do
toast=toast.makeText(getApplicationContext(),“”,toast.LENGTH\u SHORT)仍然不工作,但现在不是服务?这不是真的-您可以在
服务中使用
祝酒
,但它们必须是来自UI线程的
show()
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {

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

                            }
                        });
                    }