切换按钮以启动服务

时间:2018-10-12 02:32:20

标签: java android eclipse

我做了一个切换按钮,需要使用它来启动和停止服务。 该服务在WatcherService.java中定义,但我无法调用它。请帮助我。 这是我的MainActivity.java代码

**ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // what code is to be written here ? 
        } else {
            //  what code is to be written here ?
        }
    }
});**

3 个答案:

答案 0 :(得分:0)

要启动服务,可以使用以下代码:

                        Intent service = new Intent(buttonView.getContext(), WatcherService.java);
                        if (isChecked) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                buttonView.getContext().startForegroundService(service);
                            }else{
                                buttonView.getContext().startService(service);
                            }
                        } else {
                            buttonView.getContext().stopService(service);
                        }

请注意,在Android Oreo中,启动服务会有所不同。您可以在此处了解更多信息:https://developer.android.com/about/versions/oreo/background

答案 1 :(得分:0)

因此,基本上,您需要在已选中切换状态下启动服务,并在关闭切换状态时停止服务,这样您的逻辑就需要这样:

    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Intent service = new Intent(buttonView.getContext(), WatcherService.java);
                    if (isChecked) {
                         // start Service
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                           startForegroundService(service);
                        }else{
                           startService(service);
                        }
                    } else {
                       // stop service
                        stopService(service);
                    }
                }
            });

如果此代码位于MainActivity中,则可以,否则添加context.startService或context.stopService

答案 2 :(得分:0)

这是一个完整的示例。希望对您有帮助!

  

要启动或停止服务,请先致电startService,然后通过   操作(“ START_SERVICE” /“ STOP_SERVICE”),以便在WatcherService中   onStartCommand(),您可以决定启动或停止服务

toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // Start service
                Intent intentService = new Intent(this, WatcherService.class);
                intentService.setAction("START_SERVICE");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    this.startForegroundService(intentService);
                } else {
                    this.startService(intentService);
                }
            } else {
                Intent intentService = new Intent(this, WatcherService.class);
                intentService.setAction("STOP_SERVICE");
                Log.v(">>>", "Try to stop service");
                startService(intentService);
            }
        }
    });
  

请注意,从Android 8开始,您必须startForegroundService(   通知)。您可以了解有关前景和背景的更多信息   Foreground & Background Service

的服务
public class WatcherService extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent != null && intent.getAction() != null) {
        if (intent.getAction().equals("START_SERVICE")) {
            Log.v(">>>", "Start service");

        } else if (intent.getAction().equals("STOP_SERVICE") {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                stopForeground(true);
                stopSelf();
                Log.v(">>>", "Stop foreground service");
            } else {
                stopSelf();
                Log.v(">>>", "Stop background service");
            }

        }
    }

    return START_STICKY;
}


/**
 * Start foreground service for Android 8+
 */
@Override
public void onCreate() {
    super.onCreate();


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Title")
                .setPriority(PRIORITY_MIN)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(101, notification);
    }
}

@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager) {
    String channelId = "channel_id_01";
    String channelName = "chanel_name";
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    // omitted the LED color
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}

.......
}