将字符串值传递给后台服务

时间:2017-12-05 04:14:25

标签: java android

请指导我。感谢您的所有帮助。

我的后台服务是烘烤ABC

// ------------------- String displayedText =“ABC”; -----------------

我有两个字符串,在mainactivity.java

中声明了ABC和DEF
  1. 如何将值displayText从主活动传递给此服务。
  2. 如何在吐司ABC结束后将displayedText更改为DEF。
  3. MyService.Java

    public class MyService extends Service {
    public static final long INTERVAL=3000;//variable to execute services every 5 second
    private Handler mHandler=new Handler(); // run on another Thread to avoid crash
    private Timer mTimer=null; // timer handling
    

    //获取意图不起作用。我应该在哪里或如何使用它?

    Intent myIntent = getIntent(); 
        if (myIntent !=null && myIntent.getExtras()!=null)
    String value = myIntent.getExtras().getString(PassToService);
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("unsupported Operation");
    }
    @Override
    public void onCreate() {
    
    
        // cancel if service is  already existed
        if(mTimer!=null)
            mTimer.cancel();
        else
            mTimer=new Timer(); // recreate new timer
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
    
    }
    
    
        @Override
    public void onTaskRemoved(Intent rootIntent) {
        stopSelf();///its will stop service
        super.onTaskRemoved(rootIntent);
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
        mTimer.cancel();//cancel the timer
        super.onDestroy();
    
    }
    
    //inner class of TimeDisplayTimerTask
    private class TimeDisplayTimerTask extends TimerTask {
        @Override
        public void run() {
    
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast at every 10 second
                    //String displayingText = "ABC";
                    String displayingText = myIntent.getStringExtra("PassToService");
                    final Toast Notify = Toast.makeText(getApplicationContext(), displayingText, Toast.LENGTH_SHORT);
                    Notify.setGravity(Gravity.CENTER, 0, 0);
                    Notify.show();
    
                    Handler cancelToast = new Handler();
                    cancelToast.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Notify.cancel();
                        }
                    }, 1000);
    
                }
            });
        }
    }
    

    }

1 个答案:

答案 0 :(得分:0)

您可以通过将值从活动传递到服务来实现 -

startService(new Intent(YourActivity.Service.class).putExtra(“key”,“value”));