系统服务:service定时

布局文件:

<Button
    android:id="@+id/system_service"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/service_calc"
    android:layout_alignBottom="@+id/service_calc"
    android:layout_alignLeft="@+id/onbind_service"
    android:layout_alignStart="@+id/onbind_service"
    android:text="闹钟" />

代码:

package com.example.liu.mytesta.home.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.liu.mytesta.R;
import com.example.liu.mytesta.app.BaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyServiceActivity extends BaseActivity {

    @BindView(R.id.system_service)
    Button systemService;
    AlarmManager alarmManager;//系统服务
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_service);
        ButterKnife.bind(this);
        initSystemService();
    }

    private void initSystemService() {
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    }

    @OnClick({R.id.system_serviceiewClicked(View view) {
        switch (view.getId()) {
            case R.id.system_service://闹钟
                long time = System.currentTimeMillis();//获取当前时间
                time+=3000;//当前时间3秒后执行
                Intent i=new Intent(this,MyService.class);//启动服务
                PendingIntent operation=PendingIntent.getService(this,0,i,0);
                alarmManager.set(AlarmManager.RTC_WAKEUP,time,operation);
                break;
        }
    }
}

Serivce://只做一个简单的Toast

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ToastUtils.showToast(getApplicationContext(),"时间到了。。。。。。");
    return super.onStartCommand(intent, flags, startId);

}

猜你喜欢

转载自blog.csdn.net/weixin_41665521/article/details/81571446