持续在后台运行服务

Vin*_*oth 3 android android-intentservice

持续在后台运行服务.例如,必须启动服务,即使应用程序关闭,也会显示20秒的Toast消息.

public class AppService extends IntentService {

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    public AppService() {
        super("AppService");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        Toast.makeText(getApplicationContext(), "hai", Toast.LENGTH_SHORT).show();
        SystemClock.sleep(20000);
    }
}
Run Code Online (Sandbox Code Playgroud)

Vin*_*oth 6

下面的代码适合我......

public class AppService extends Service {

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

@Override
public void onCreate() {
    Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}
}
Run Code Online (Sandbox Code Playgroud)