java - 单击启动和停止计时器服务

标签 java android service timer

我有一个在后台运行的服务,每 15 分钟就会显示一个通知或对话框。但是我怎样才能让它启动和停止 FAB 的 OnClick 呢? 当前,该按钮在 OnClick 时显示 Snack Bar。我想添加 If/Else 代码来启动和停止服务。我怎样才能做到这一点?

这是服务:

public class SafeService extends Service {
private Handler mHandler = new Handler();
private Timer mTimer = null;
public static final int NOTIFICATION_ID = 1;
public static final long NOTIFY_INTERVAL = 900 * 1000; // 15 Minutes
/*^TODO - TEST NOTIFY_INTERVAL FOR ACCURACY^*/

/*^Those are for the timer and handler so the code
can recognise it^ The last one gives how long the timer runs */
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    // Cancels the timer if it already existed.
    if (mTimer != null) {
        mTimer.cancel();
    } else {
        // recreate new
        mTimer = new Timer();
    }
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                // Lollipop or Above
                if (Build.VERSION.SDK_INT >= 21) {
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(SafeService.this);
                    new NotificationCompat.Builder(SafeService.this);
                    builder.setSmallIcon(R.drawable.smallplaceholder);
                    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
                    builder.setContentTitle("Safeguard");
                    builder.setContentText("Be careful, Trainer! Remember to look up and stay aware of your surroundings!!");
                    builder.setStyle(new NotificationCompat.BigTextStyle().bigText("Be careful, Trainer! Remember to look up and stay aware of your surroundings!!"));
                    builder.setPriority(Notification.PRIORITY_HIGH);
                    builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    notificationManager.notify(NOTIFICATION_ID, builder.build());
                    //Below Lollipop
                } else {
                    new MaterialDialog.Builder(SafeService.this)
                            .title(R.string.warning_title)
                            .content(R.string.warning)
                            .positiveText(R.string.button_ok)
                            .show();
                }

            }
        });

            }

        };
    }

这是我想要启动和停止服务的按钮:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Safeguard is now on!", Snackbar.LENGTH_LONG).show();
//Start service after showing SnackBar
        }
    });

最佳答案

您可以使用一个 Singleton 实例来绑定(bind)/取消绑定(bind)您的服务,这样,如果您的 Activity 被 Android 销毁,该服务将不会被取消绑定(bind):

ServiceSingleton.java:

public class ServiceSingleton {

    private String TAG = ServiceSingleton.class.getSimpleName();

    private static ServiceSingleton mInstance;

    private Context mContext;

    private boolean mBound = false;

    private SafeService mService;

    private ServiceConnection mServiceConnection = null;

    public static ServiceSingleton getInstance(Context context) {
        if (mInstance == null)
            mInstance = new ServiceSingleton(context);
        return mInstance;
    }

    private ServiceSingleton(Context context) {
        this.mContext = context.getApplicationContext();
    }

    public boolean startNotification() {

        if (!mBound) {

            mServiceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder service) {

                    Log.i(TAG, "onServiceConnected");

                    mService = ((SafeService.LocalBinder) service).getService();

                    mService.startNotification();
                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {
                }
            };

            Intent intent = new Intent(this, SafeService.class);
            mBound = mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

            if (!mBound) {
                Log.e(TAG, "Error cant bind to service !");
            }
        } else {
            if (mService != null) {
                mService.startNotification();
            }
        }
        return mBound;
    }

    public void stopNotification() {
        if (mBound && mService != null) {
            mService.stopNotification();
        }
    }

    public boolean isNotificationStarted() {
        if (mBound && mService != null) {
            return mService.isNotificationStarted();
        }
        return false;
    }

    public void close() {
        try {
            if (mBound) {
                if (mService!=null){
                    mService.stopNotification();
                }
                mContext.unbindService(mServiceConnection);
                mBound = false;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    public boolean isBound() {
        return mBound;
    }
}

在你的onCreate()

mSingleton = ServiceSingleton.getInstance();

对于您的点击监听器:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        if (mSingleton.isNotificationStarted()){
            mSingleton.startNotification(); 
        }
        else {
            mSingleton.stopNotification();
        }

    }
});

stopNotification() 如果您想重用它,则不会取消绑定(bind)服务,如果您想关闭它,请调用 close()

关于java - 单击启动和停止计时器服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38427201/

相关文章:

c# - 加载空字符串和 Silverlight 4

java - 如何在netbeans整个项目中进行高级搜索?

java - 为什么 Java 经常用于企业应用程序?

android - 无法让 getLastLocation 方法在 Android Studio 中工作

java - Android 内存泄漏在设备上,而不是在模拟器上

android - 尝试使用回收位图 android.graphics.Bitmap

android - 带有计时器的android媒体播放器服务

java - 在 Java 中将大型二进制字符串转换为十进制

java - GridView.setOnItemClickListener 触发整行

android - 线性布局的圆角选择