将EditText的值传递给服务

时间:2015-05-20 10:19:49

标签: android

我有一个简单的Activity来创建一个前台服务。我想将EditText中的值传递给Service,因为屏幕应该变暗。 MainActivity看起来像这样:

package com.mycompany.myapp;

import android.app.*;
import android.content.*;
import android.net.*;
import android.net.wifi.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.provider.*;
import android.text.*;


public class MainActivity extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final EditText edDim = (EditText) findViewById(R.id.DimVal);
        edDim.setInputType(InputType.TYPE_CLASS_NUMBER);

        Button btnStart =(Button) findViewById(R.id.button1);
        btnStart.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                Intent intent = new Intent(getBaseContext(), MyService.class);
                intent.putExtra("DimVal",edDim.getText());
                startService(intent);
            }
        });

        Button btnStop =(Button) findViewById(R.id.button2);
        btnStop.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View v){
                    stopService(new Intent(getBaseContext(), MyService.class));
                }
            });

    }
}

这是服务:

    package com.mycompany.myapp;
import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.provider.*;
import android.view.*;
import android.widget.*;

public class MyService extends Service
{
public int timeVal;
    @Override
    public IBinder onBind(Intent p1)
    {
        // TODO: Implement this method
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        // TODO: Implement this method
        Toast.makeText(this,"Usługa uruchomiona",Toast.LENGTH_LONG).show();
        timeVal = intent.getIntExtra("DimVal",100);
        this.registerReceiver(this.mComnReceiver,
                              new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        Notification note = new Notification(0, null,
        System.currentTimeMillis());note.flags = Notification.FLAG_NO_CLEAR;
        this.startForeground(1,note);
        return START_STICKY;
    }

    /*@Override
    public void onDestroy()
    {
        // TODO: Implement this method
        super.onDestroy();
        Toast.makeText(this,"Usługa zatrzymana",Toast.LENGTH_LONG).show();
    }*/

    private BroadcastReceiver mComnReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context p1, Intent p2)
        {
            ConnectivityManager manager = (ConnectivityManager) 
              getSystemService(CONNECTIVITY_SERVICE);
            boolean isWiFi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();


            //NetworkInfo currentNetworkInfo = (NetworkInfo)
                //p2.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

            if(isWiFi){
                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, timeVal);

            }else{

                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 300);

            }

        }


    };
}

但上面的代码不起作用。如果WiFi每5分钟一次,我该如何检查服务?我意识到这个代码可能不是问题的最佳解决方案,但这是我编写的第一个Android程序(因此是注释代码)。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

        public void timerForWifiCheck(long intervalVal, long countVal) {

                    new SCBP_TimerClass(intervalVal, countVal) {
                        @Override
                        public void onTick(long tickTime) {

                            //Wifi checking code write here
                      if(SCBP_NetworkUtil.checkInternetConnection(Context)){
                      //Do what you wnat e.g
                      finish()
                    }else{
                       //Return with some error code or msg
                    }

                            }
                        }
                        @Override
                        public void onFinish() {
                            //code when the  timer finshes 
                        }
                    }.start();
                }






    For this You need to add the below  two classes:


        public abstract class TimerClass {

        /**
         * Millis since epoch when alarm should stop.
         */
        private final long mMillisInFuture;

        /**
         * The interval in millis that the user receives callbacks
         */
        private final long mCountdownInterval;

        private long mStopTimeInFuture;

        private long mPauseTime;

        private boolean mCancelled = false;

        private boolean mPaused = false;

        /**
         * @param millisInFuture
         *            The number of millis in the future from the call to
         *            {@link #start()} until the countdown is done and
         *            {@link #onFinish()} is called.
         * @param countDownInterval
         *            The interval along the way to receive {@link #onTick(long)}
         *            callbacks.
         */
        public SCBP_TimerClass(long millisInFuture, long countDownInterval) {
            mMillisInFuture = millisInFuture;
            mCountdownInterval = countDownInterval;
        }

        /**
         * Cancel the countdown.
         * 
         * Do not call it from inside CountDownTimer threads
         */
        public final void cancel() {
            mHandler.removeMessages(MSG);
            mCancelled = true;
        }

        /**
         * Start the countdown.
         */
        public synchronized final SCBP_TimerClass start() {
            if (mMillisInFuture <= 0) {
                onFinish();
                return this;
            }
            mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
            mHandler.sendMessage(mHandler.obtainMessage(MSG));
            mCancelled = false;
            mPaused = false;
            return this;
        }

        /**
         * Pause the countdown.
         */
        public long pause() {
            mPauseTime = mStopTimeInFuture - SystemClock.elapsedRealtime();
            mPaused = true;
            return mPauseTime;
        }

        /**
         * Resume the countdown.
         */
        public long resume() {
            mStopTimeInFuture = mPauseTime + SystemClock.elapsedRealtime();
            mPaused = false;
            mHandler.sendMessage(mHandler.obtainMessage(MSG));
            return mPauseTime;
        }

        /**
         * Callback fired on regular interval.
         * 
         * @param millisUntilFinished
         *            The amount of time until finished.
         */
        public abstract void onTick(long millisUntilFinished);

        /**
         * Callback fired when the time is up.
         */
        public abstract void onFinish();

        private static final int MSG = 1;

        // handles counting down
        private Handler mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {

                synchronized (SCBP_TimerClass.this) {
                    if (!mPaused) {
                        final long millisLeft = mStopTimeInFuture
                                - SystemClock.elapsedRealtime();

                        if (millisLeft <= 0) {
                            onFinish();
                        } else if (millisLeft < mCountdownInterval) {
                            // no tick, just delay until done
                            sendMessageDelayed(obtainMessage(MSG), millisLeft);
                        } else {
                            long lastTickStart = SystemClock.elapsedRealtime();
                            onTick(millisLeft);

                            // take into account user's onTick taking time to
                            // execute
                            long delay = lastTickStart + mCountdownInterval
                                    - SystemClock.elapsedRealtime();

                            // special case: user's onTick took more than
                            // interval to
                            // complete, skip to next interval
                            while (delay < 0)
                                delay += mCountdownInterval;

                            if (!mCancelled) {
                                sendMessageDelayed(obtainMessage(MSG), delay);
                            }
                        }
                    }
                }
            }
        };
        }

public class NetworkUtil {
    public static boolean checkInternetConnection(Context context) {

        ConnectivityManager con_manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}


    Hope this will help you to some extent.Cheers!

答案 1 :(得分:0)

我发现问题在于这行代码

intent.putExtra("DimVal",edDim.getText());

你应该这样做

intent.putExtra("DimVal",Integer.valueOf(edDim.getText().toString));

EditText getText,即edDim.getText()将为您提供可编辑而非内部值。另外,您将执行edDim.getText().toString将为您提供在传递之前更改为Integer所需的字符串值。

注意:在传递intent中的值之前,您需要为edDim设置null并检查验证;否则它可能会给你运行时错误。

关于WiFi的检查,最好创建一个接收连接检查更新的广播接收器,如果有连接,那么你可以检查它是Wifi还是移动数据,如果是移动数据则返回false。这样您就不需要每隔五分钟检查一次,这可能导致电池排水。

您可以查看Determining and Monitoring the Connectivity Status的此Android开发人员帖子。