每5秒钟后无法在服务中显示Toast

时间:2017-10-23 07:56:58

标签: android service toast

当我尝试在服务中干杯时它不起作用但是当我使用LOg它工作正常我该如何解决这个问题? 这是我的代码请检查: 主要活动

public class MainActivity extends AppCompatActivity {

Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn =(Button) findViewById(R.id.btnDownload);
    Intent in= new Intent(this,MyService.class);
    startService(in);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(getApplicationContext(),Main2Activity.class);
            startActivity(i);
        }
    });
}

我的服务类:如果我使用Log而不是Toast它可以工作,但是当我使用Toast它没有显示任何东西时......

public class MyService extends Service {
public MyService() {
}


@Override
public int onStartCommand(Intent intent,  int flags, int startId) {
   Runnable r=new Runnable() {
        @Override
        public void run() {
            for (int i=0 ; i<5 ; i++){
                long futureTime = System.currentTimeMillis()+5000;
                while (System.currentTimeMillis() < futureTime){
                    synchronized (this){
                        try {
                            wait(futureTime-System.currentTimeMillis());
                            Toast.makeText(getApplicationContext(),"Image Downloading",Toast.LENGTH_SHORT);
                        }catch (Exception e){}
                    }
                }
            }

        }
    };
    Thread razasThread = new Thread(r);
    razasThread.start();
    return Service.START_STICKY;
}

@Override
public void onDestroy() {
    Toast.makeText(getApplicationContext(),"OnDestroy method Called",Toast.LENGTH_SHORT).show();
}

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

}

1 个答案:

答案 0 :(得分:1)

尝试使用Handler进行操作。它可能会抛出一个异常,因为你试图在另一个线程上显示Toast:

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

@Override
public void run() {
     for (int i=0 ; i<5 ; i++){
            long futureTime = System.currentTimeMillis()+5000;
            while (System.currentTimeMillis() < futureTime){
                synchronized (this){
                    try {
                        wait(futureTime-System.currentTimeMillis());
                        Toast.makeText(getApplicationContext(),"Image Downloading",Toast.LENGTH_SHORT).show();
                    }catch (Exception e){}
                }
            }
        }            
}
});