android - 将参数从activity传递给服务并停止服务

时间:2014-02-23 18:47:30

标签: android android-service

我的活动中有两个复选框。首先,我想向我的服务发送一些参数,然后如果用户取消选中该服务停止的方框。这是我的代码剪辑

这里我从MainActivity传递参数但我没有在服务中获取

Intent serviceIntent=new Intent(MainActivity.this,MyService.class);
serviceIntent.putExtra("name", "image");
startService(serviceIntent);

服务类

public class MyService extends Service {

String selectedAudioPath = "";
private MyThread myythread;
public Intent intent;
public boolean isRunning = false;
long interval=30000;

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

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

    myythread  = new MyThread(interval);

}

@Override
public synchronized void onDestroy() {
    super.onDestroy();
    if(!isRunning){
        myythread.interrupt();
        myythread.stop();
    }
}

@Override
public synchronized void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    if(!isRunning){
        this.intent = intent;

        myythread.start();
        isRunning = true;
    }
}

class MyThread extends Thread{
    long interval;
    public MyThread(long interval){
        this.interval=interval;
    }
    @Override
    public void run(){
        while(isRunning){
            System.out.println("Service running");
            try {

                Bundle extras = intent.getExtras(); 
                if(extras == null)
                    Log.d("Service","null"); // i am getting null here 
                else
                {
                    Log.d("Service","not null");
                    String from = (String) extras.get("name");
                    if(from.equalsIgnoreCase("image")){
                        uploadImages();
                    Thread.sleep(interval);
                }else if(from.equalsIgnoreCase("audio")){

                    uploadAudio();
                    Thread.sleep(interval);
                } }



            } catch (InterruptedException e) {
                isRunning = false;
                e.printStackTrace();
            }
        }
    }

第二件事我想停止服务,如果在进程用户取消选中该框。我遵循了这个问题How to pass a parameter from an activity to a service...when the user stop the service我遵循了每一步,但是当我写这一行时我陷入困境

registerReceiver(new UserStopServiceReceiver(),  newIntentFilter(USER_STOP_SERVICE_REQUEST));

newIntentFilter上给我一个错误。我必须在某处宣布

1 个答案:

答案 0 :(得分:0)

首先,在你的意图中,你没有指定任何包,只是一个字符串。所以,替换这个

Bundle extras = intent.getExtras();

用这个

String myString = intent.getStringExtra("name");

关于第二个问题:

CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform logic
        }

    }
});