3

我正在实现在后台运行服务,服务将停止并开始单击切换按钮。服务在第一个活动中启动,并在单击切换按钮时在另一个活动中停止服务。当我运行应用程序服务时自动启动我在第一个活动的 onCreate() 方法中启动的第一个活动和另一个活动切换按钮状态已经处于状态但是当我切换按钮将关闭服务停止但当我回到第一个活动时服务再次启动。请任何人帮帮我。这是我的代码

public class MyService extends Service
{
    private static final String TAG = "MyService";
    MediaPlayer player;
    private final String StrMyService="myservice";



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setLooping(false); // Set looping
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        player.start();
    }
}




public class Service_Demo extends Activity implements OnClickListener 
{
      private static final String TAG = "ServicesDemo";


      @Override
      public void onCreate(Bundle savedInstanceState)
      {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        System.out.println("In OnCreate(");
        startService(new Intent(this, MyService.class));


      }
}


public class Toggle_Activity extends Activity
{
    ToggleButton tgButton;
    private boolean isService=false;
    private String strService;
    public final String service_Prefs="servicePrefs";
    private static final String StrMyService = "zdf";


    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.toggle);

        final SharedPreferences servicePrefs=this.getSharedPreferences("Service_Prefs",MODE_WORLD_READABLE);
        strService=servicePrefs.getString(StrMyService , "myservice");
        Log.e("",""+strService);

        final boolean mBool = servicePrefs.getBoolean("myservice", true);
        Log.e("Boolean Value mBool","="+mBool);
        Boolean b = mBool;
        Log.e("Update pref", b.toString());

        tgButton = (ToggleButton)findViewById(R.id.toggleButton);
        tgButton.setChecked(mBool);




        final boolean mBool1 = servicePrefs.getBoolean("myservice", false);
            final Boolean c = mBool1;
        Log.e("Update pref", c.toString());


        tgButton=(ToggleButton)findViewById(R.id.toggleButton);
        tgButton.setOnClickListener(new OnClickListener()

      {

            @Override
            public void onClick(View v) 
                  {
                // TODO Auto-generated method stub

                if(tgButton.isChecked())
                {
                    startService(new Intent(Toggle_Activity.this , MyService.class));
                    System.out.println("Service is started in togglr button");

                }
                else
                {   

                    stopService(new Intent(Toggle_Activity.this,MyService.class));
                    System.out.println("Service is stopped in togglr button");

                }
            }
        });


    }

}
4

2 回答 2

0

在第一个活动中,您将 startService(new Intent(this, MyService.class)) 从 oncreate 放入 onresume

于 2013-05-14T07:04:07.077 回答
0

我想出了最好的方法。我基本上使用共享的偏好和听众将我的切换按钮和我的服务链接在一起。我将此共享首选项称为“service_running”,然后onCreate()在切换按钮所在的活动方法中实现我的侦听器(在本例中,MainActivity.

在我的onCreate()继承人中我做了什么:

    // set toggle button based on service running
    final ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton);
    toggle.setChecked(serviceRunning(SendService.class));
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                startSendService();
            }
            else {
                stopSendService();
            }
        }
    });

    // set shared pref listener for toggle
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.OnSharedPreferenceChangeListener myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if (key.equals("service_running")) {
                toggle.setChecked(prefs.getBoolean("service_running", false));
            }
        }
    };
    prefs.registerOnSharedPreferenceChangeListener(myPrefListner);

startSendService()并且stopSendService()只需根据它是否正在运行以及是否具有正确的应用程序权限来启动或停止我的服务。

这是检查服务是否正在运行的方法(归功于此线程中的@geekQ ):

private boolean serviceRunning (Class<?> serviceClass) {
    // check if a service class is currently running
    ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }

    return false;
}

然后在我的服务中,在 onStartCommand() 中我只是将共享首选项更改为true,在 onDestroy() 中我将其更改为false.

唯一需要注意的是,您必须从偏好屏幕中隐藏此共享偏好,这可以通过以下方式完成:

getPreferenceScreen().removePreference(findPreference("service_running"));
于 2017-02-07T03:59:06.740 回答