切换按钮以启动服务

Posted

技术标签:

【中文标题】切换按钮以启动服务【英文标题】:toggle button to start a service 【发布时间】:2019-03-17 04:52:49 【问题描述】:

我制作了一个切换按钮,我需要使用它来启动和停止服务。 该服务是在 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 ?
        
    
);**

【问题讨论】:

【参考方案1】:

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

                        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

【讨论】:

【参考方案2】:

所以基本上你需要在切换检查时启动服务并在切换关闭时停止服务所以你的逻辑应该是这样的:

    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

【讨论】:

【参考方案3】:

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

要启动或停止服务,你们都调用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;


.......

【讨论】:

以上是关于切换按钮以启动服务的主要内容,如果未能解决你的问题,请参考以下文章

在onClick上启动服务

如何在页面加载后启动 Bootstrap 切换按钮,如果打开则不调用回调

如何停止以自定义意图启动的 Android 服务

android 怎样启动后台服务

mySql提示服务启动后停止应该如何去解决

Linux的系统启动流程